0

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,

// 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

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.

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

Anyone knows what I am doing wrong or how can I fix this? Thanks

7
  • So are you saying that without ,0, it works and shows you the inner text of both of those script elements? If not, then that would mean your selector doesn’t match the elements to begin with. Commented Apr 17, 2020 at 11:17
  • @CBroe exactly. If I dont use "0" or anything else than it shows me the data from both script tags. Commented Apr 17, 2020 at 11:18
  • 1
    I guess trying to loop over this in case where you requested only one specific element to be returned, is wrong to begin with. find('foo') returns an array, find('foo', 0) returns one specific element. Does $script = $html->find('script[type="application/ld+json"]',0); echo $script->innertext; get you what you need? Commented Apr 17, 2020 at 11:21
  • should I tell you the var_dump result or try the above code you posted just now? Commented Apr 17, 2020 at 11:22
  • Nigel’s answer already confirms my suspicion, so just use their code and it should work. Commented Apr 17, 2020 at 11:23

1 Answer 1

1

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)...

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

Just for reference, the code from 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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.