简体   繁体   中英

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": ... } ;
</script>

Thank you for your time and answers :).

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

Okay If you want to store that javascript variable in PHP then, you might have to send that variable to any PHP file using GET or POST method with ajax.

you can send the var serializedForm = {"fields": ... } ; in ajax as a post or get method and in ajax.php file get this variable under $_POST or $_GET and save it to php variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM