I am using simple html dom to parse a link that contains two script tags with type=application/ld+json.
The target website structure is like below,
JavaScript
x
// 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>
Now as I showed above I just want to parse the data inside the first , For this I am using following code
JavaScript
foreach($html->find('script[type="application/ld+json"]',0) as $name)
{
echo $name->innertext;
}
As I am trying to extract the first occurrence of by specifying “0” in find() function but that give me the following error.
JavaScript
Trying to get property of non-object in C:xampphtdocshtmldomexampleexample_basic_selector.php on line 14
Anyone knows what I am doing wrong or how can I fix this? Thanks
Advertisement
Answer
If you specify the index of the instance you want, you only get that element back and not a list, so the loop isn’t required (in fact is the problem)…
JavaScript
$json = $html->find('script[type="application/ld+json"]',0);
echo $json->innertext;
Just for reference, the code from find()
…
JavaScript
// 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;