如何从HTML页面获取Javascript变量? [英] How to get Javascript variable from an HTML page?

查看:266
本文介绍了如何从HTML页面获取Javascript变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在互联网页面的源代码中,有一个Javascript变量,该变量包含要存储在PHP程序中的JSON数据.

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?

该文件位于公共html链接上,看起来像这样:

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 :).

推荐答案

您对"Internet上的页面"和公共"这两个词的使用使我认为您没有写该页面,而您只能访问到源代码. 在这种情况下,您可能必须以纯文本形式检索变量,然后将其解析为JSON.

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.

首先以纯HTML格式获取页面内容

First get the page content as plain html

$html = file_get_contents($yourURL);

然后找到您要查找的行

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

这应该为您提供整个JSON变量以及赋值部分(var serializedForm =).

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

这篇关于如何从HTML页面获取Javascript变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆