Eryen S Eryen S - 1 year ago 60
JSON Question

How to get Javascript variable from an HTML page?

In the source code of a page on the internet, there is a Javascript variable containing JSON data that I would like to store in a variable in my PHP program.

Any idea about how to do it?

The file is on a public html link and it looks like this:

<script type="text/javascript">
var serializedForm = {"fields": ... } ;

Thank you for your time and answers :).

Answer Source

Your use of the words "a page on the Internet" and "public" makes me think that you didn't write the page and that you only have access to the source code. In that case you might have to retrieve the variable as plain text and then parse it as JSON.

First get the page content as plain html

$html = file_get_contents($yourURL);

Then find the line you are looking for

$javascriptVar = preg_grep("/var serializedForm = {.*}/", $html);

This should get you the entire JSON variable as well as the assignment part (var serializedForm =).

Get rid of it by either running another regex match or manually counting the amount of characters to remove and then parse your variable.

$result = json_decode($javascriptVar);