简体   繁体   English

使用 PHP Simple HTML DOM 提取脚本内容

[英]Extract the content of the script with PHP Simple HTML DOM

I want to extract the content of the script on this page , which has the ID __NEXT_DATA__ using PHP Simple HTML DOM , the code I wrote is this:我想提取这个页面上脚本的内容,它的 ID __NEXT_DATA__ using PHP Simple HTML DOM ,我写的代码是这样的:

foreach($html_base->getElementsByTagName('script') as $element) {
                if (isset($element->id)){
                    $id = $element->id;
                    if ($id == "__NEXT_DATA__"){
                        $f = $element->nodeValue;
                        echo $f;
                        break;
                    }
                }
            
            }

but unfortunately it gives me the following error:但不幸的是,它给了我以下错误:

Undefined property: DOMElement::$id

You can use simple html dom documentation but here's my suggestion:您可以使用简单的 html dom 文档,但这是我的建议:

$html = file_get_html("url");
$script = $html->find("script[id=__NEXT_DATA__]", 0)->innertext;

the second parameter which is 0, is the index of the searched results and because it's only one script with this id, you can take the first result.第二个参数为 0,是搜索结果的索引,因为它只有一个具有此 id 的脚本,所以您可以获取第一个结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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