Donato Micele Donato Micele - 9 days ago 5x
JSON Question

Get JavaScript var value from a web page

In a php program, I have a web page in $page variable.

$page = file_get_contents("", false, $context);

$dom = new DOMDocument;
$xpath = new DOMXPath($dom);

In this page there are some javascript and I want to take the json data contained in the variable called "evtsVar".

<script ...>
<script ...>
var evtsVar = {json data}

Use Xpath query is the right method? How can I do to take this variable value?

Thank you all and sorry for my English.


This is a very specific question about a certain page. I've analyzed the page you have provided the link. There is a variable within a script tag. You want to get that in JSON.

I've used jquery for the solution, strongly recommended for you too.

Get the page first:


$page = file_get_contents("", false, $context);


Then get the page in a javascript variable:

var page = <?php echo json_encode( $page ) ?>;

Now we have the page, we should find the string starting with "var evtsVar = ", ending with ";":

var preString = "var evtsVar = ";
var postString = ";";
var preIndex = page.indexOf( preString );
var searchIndex = preIndex + page.substring( preIndex ).indexOf( postString );

var evtsString = page.slice( preIndex + preString.length , searchIndex );

Now get parse the string to a json object and print:

var evtsVar = JSON.parse( evtsString );

console.log( evtsVar );

Tested, works.