使用 SimpleHtmlDom - PHP 从脚本标记的出现中解析 JSON 数据

我正在使用简单的 html dom 来解析一个链接,该链接包含两个类型为 application/ld+json 的脚本标签。


目标网站结构如下,


// tag that I want to parse

<script type="application/ld+json">

Some JSON Data

</script>



// tag that I **do not want** to parse

<script type="application/ld+json">

Some JSON Data

</script>

现在正如我上面所示,我只想解析第一个中的数据,为此我使用以下代码


foreach($html->find('script[type="application/ld+json"]',0) as $name)

{

   echo $name->innertext;

}

当我试图通过在 find() 函数中指定“0”来提取第一次出现时,但这给了我以下错误。


Trying to get property of non-object in C:\xampp\htdocs\htmldom\example\example_basic_selector.php on line 14

任何人都知道我做错了什么或者我该如何解决这个问题?谢谢


开满天机
浏览 62回答 1
1回答

白衣非少年

如果您指定所需实例的索引,则只会返回该元素而不是列表,因此不需要循环(实际上是问题所在)...$json = $html->find('script[type="application/ld+json"]',0);echo $json->innertext;仅供参考,代码来自find()...&nbsp; &nbsp; // return nth-element or array&nbsp; &nbsp; if (is_null($idx)) return $found;&nbsp; &nbsp; else if ($idx<0) $idx = count($found) + $idx;&nbsp; &nbsp; return (isset($found[$idx])) ? $found[$idx] : null;
打开App,查看更多内容
随时随地看视频慕课网APP