I have a php variable of javascript code which was parsed from another page. Is there a simple way to access the javascript variables individually with php?

PHP:

$cool = "<script type='text/javascript'>
var Title = 'This is the title';
var Text = 'Some text here';

Title.info.showinfo({

    'thumb':'image.jpg',
    'date':'Oct 2',
    'year':'2011'

});
</script>";

What Im trying to accomplish:

$title = "This is the title";
$text = "Some text here";
$thumb = "image.jpg";
$date = "Oct 2";
$year = "2011";
share|improve this question

2  
If the other page cooperates with you, get the data from it as JSON and all will be fine. Otherwise I don't envy you. – Jon Oct 28 '11 at 21:32
Try this: timwhitlock.info/blog/2009/11/14/… a PHP-based JS parser/tokenizer. Should let you extract those fairly easily. – Marc B Oct 28 '11 at 21:34
If your input follows a solid pattern, use a RegExp: php.net/manual/en/function.preg-match.php – Rob W Oct 28 '11 at 21:34
I ended up using RegExp – supercoolville Oct 29 '11 at 19:23
feedback

2 Answers

try something like this,

<?php
$data = array(
    'key1' => 'value1',
    'key2' => 'value2'
);
$str = "some string";
?>

then output it using JSON data format,

<script type='text/javascript'>
var data = <?php echo json_encode($data);?>;
var str = <?php echo json_encode($str);?>;

alert(data.key1); // value1
alert(str); // some string
</script>
share|improve this answer
may be i missed something in your question, :D – Lee Oct 29 '11 at 7:28
nope, your answer is correct. – Your Common Sense Oct 29 '11 at 7:42
feedback

It's not javascript yet. It's just a piece of string. And there's no simple way to get those values from PHP. Some ways are.

  1. Dive into the string(code) and get the values by explode()ing or pattern matching with regex.

  2. Send the code to client first, let the javascript run and send back via AJAX.

  3. If you have control of the javascript code, make the variables accessible by PHP in the first place.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.