How to get Javascript variable from an HTML page?

后端 未结 2 796
花落未央
花落未央 2021-01-22 09:06

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 ab

相关标签:
2条回答
  • 2021-01-22 09:27

    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.

    0 讨论(0)
  • 2021-01-22 09:33

    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);
    
    0 讨论(0)
提交回复
热议问题