1

Need to open $link with javascript, that is retrieved from an XML file using PHP. Here's the code:

<?php

$url = "map.xml" ;
$xml = simplexml_load_file($url);
$link = $xml->url[mt_rand(0,count($xml->url)-1)]->loc ; // Get Random Location 
?>

<html>
<head>
    <title></title>
</head>
<body>
<script>
  $(document).ready(function(){
      window.open($link, "_blank"); // will open new tab on document ready
  });
</script>
</body>
</html>

1 Answer 1

3

You cannot access php variables from javascript. With php you can render html and javascript on server. So you need to print your $link variable to the page:

window.open("<?= $link ?>", "_blank");

Note that short echo tag <?= is only guaranteed to be available on php 5.4+, if you are stuck supporting an older version use <?php echo instead

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, fantastic. Thank you! That worked (not sure why I overlooked the obvious). cheers
Because it's a language feature that makes things easier. And it's good coding style to make use of language features as much as you can.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.