supercoolville
supercoolville

Reputation: 9086

Accessing Javascript In PHP variable

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";

Upvotes: 0

Views: 268

Answers (2)

Lee
Lee

Reputation: 3329

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>

Upvotes: 1

Moe Sweet
Moe Sweet

Reputation: 3721

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.

Upvotes: 0

Related Questions