为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
开满天机 2022-12-30 15:59:38
我正在使用简单的 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任何人都知道我做错了什么或者我该如何解决这个问题?谢谢
查看完整描述

1 回答

?
白衣非少年

TA贡献1155条经验 获得超0个赞

如果您指定所需实例的索引,则只会返回该元素而不是列表,因此不需要循环(实际上是问题所在)...


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

echo $json->innertext;

仅供参考,代码来自find()...


    // return nth-element or array

    if (is_null($idx)) return $found;

    else if ($idx<0) $idx = count($found) + $idx;

    return (isset($found[$idx])) ? $found[$idx] : null;


查看完整回答
反对 回复 2022-12-30
  • 1 回答
  • 0 关注
  • 61 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信