[英]Get JavaScript var value from a web page
In a php program, I have a web page in $page variable.在 php 程序中,我在 $page 变量中有一个网页。
...
$page = file_get_contents("http://www.autostrade.it/autostrade-gis/gis.do", false, $context);
$dom = new DOMDocument;
$dom->loadHTML($);
$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".在此页面中有一些 javascript,我想获取名为“evtsVar”的变量中包含的 json 数据。
...
<script ...>
...
</script>
<script ...>
...
var evtsVar = {json data}
...
</script>
Use Xpath query is the right method?使用Xpath查询是正确的方法吗? 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.你想在 JSON 中得到它。
I've used jquery for the solution, strongly recommended for you too.我已经使用 jquery 作为解决方案,强烈推荐给你。
Get the page first:先获取页面:
<?
$page = file_get_contents("http://www.autostrade.it/autostrade-gis/gis.do", false, $context);
?>
Then get the page in a javascript variable:然后在 javascript 变量中获取页面:
var page = <?php echo json_encode( $page ) ?>;
Now we have the page, we should find the string starting with "var evtsVar = ", ending with ";":现在我们有了页面,我们应该找到以“var evtsVar =”开头,以“;”结尾的字符串:
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:现在将字符串解析为 json 对象并打印:
var evtsVar = JSON.parse( evtsString );
console.log( evtsVar );
Tested, works.经测试,有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.