phpdomhtml-parsingsimple-html-dom

How to parse a p tag content with no class and no id using SimpleHTMLdom parser?


this is the html part i want to parse in order to get the text inside the <p> :

<div class="container">
    <h2>title</h2>
    <div class="divIdontNeed"> hi </div>
    <p> I WANT THIS TEXT </p> <====== this is what i want
    <p> i don't want this one </p>
</div>

What i did is a loop (because the html above is on multiple pages and i want all of them on an array $allTexts) :

foreach($html->find('div[class=container]')->find('p',0) as $text){

                    array_push($allTexts, $text->plaintext);
                }

When i do that, i got an error saying Fatal error: Call to a member function find() on array in /path/to/MyTextParser.php

Thank you all


Solution

  • You are getting the error because the first find() returns an array of elements, not just one.

    You need to do the loop on the results of that first find():

    foreach($html->find('div[class=container]') as $element)
    {
       foreach ($element->find('p',0) as $text){
       array_push($allTexts, $text->plaintext);
      }
     }