0

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";
3
  • 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. Commented Oct 28, 2011 at 21:32
  • Try this: timwhitlock.info/blog/2009/11/14/… a PHP-based JS parser/tokenizer. Should let you extract those fairly easily. Commented Oct 28, 2011 at 21:34
  • If your input follows a solid pattern, use a RegExp: php.net/manual/en/function.preg-match.php Commented Oct 28, 2011 at 21:34

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

may be i missed something in your question, :D
0

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.

Comments

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.