使用 SimpleHtmlDom 从出现的脚本标记中解析 JSON 数据 - PHP
Parse JSON data inside from occurrence of script tag using SimpleHtmlDom - PHP
我正在使用简单的 html dom 来解析 link,其中包含两个类型为 =application/ld+json.[=15 的脚本标签=]
目标网站结构如下,
// 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
任何人都知道我做错了什么或者我该如何解决这个问题?谢谢
如果指定所需实例的索引,则只会返回该元素而不是列表,因此不需要循环(实际上是问题所在)...
$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;
我正在使用简单的 html dom 来解析 link,其中包含两个类型为 =application/ld+json.[=15 的脚本标签=]
目标网站结构如下,
// 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
任何人都知道我做错了什么或者我该如何解决这个问题?谢谢
如果指定所需实例的索引,则只会返回该元素而不是列表,因此不需要循环(实际上是问题所在)...
$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;