0

I have an HTML as so:

 <html>
   <body>
      <div class="somethingunneccessary"></div>
      <div class="container">
         <div>
            <p>text1</p>
            <p>text2</p>
            <p>text3</p>
         </div>
         <div>
            <p>text4/p>
            <p>text5</p>
            <p>text6</p>
         </div>
         <div>
            <p>text7</p>
            <p>text8</p>
            <p>text9</p>
         </div>
         <div>
            <p>text10</p>
            <p>text11</p>
            <p>text12</p>
         </div>
         <div>
            <p>text13</p>
            <p>text14</p>
            <p>text15</p>
         </div>
      </div>
   </body>
 </html>

What I'm trying to accomplish is the following:

1./ Loop over the div elements within the div having a class container.

2./ During the iteration I want to grab the text from the 3rd p tag.

The looping part is essential instead of just slicing out the p tags by themselves

I've got some code done but it doesn't do looping:

$doc=new DOMDocument(); 
$doc->loadHTML($htmlsource);
$xpath = new DOMXpath($doc);
$commentxpath = $xpath->query("/html/body/div[2]/div[5]/p[3]");
$commentdata = $commentxpath->item(0)->nodeValue;

How do I loop through each inner div element and extract the 3rd p tag.

Like I said, the looping is essential.

slicks1
  • 349
  • 1
  • 13

3 Answers3

0

You may have to query over attributes: php xpath get attribute value

 $xpath->query("/html/body/div[@class='container']");
Community
  • 1
  • 1
Steffomio
  • 356
  • 3
  • 6
0

Just try

/html/body/div/div//p

That should return only the p elements XD

victor sosa
  • 899
  • 13
  • 27
0

During the iteration I want to grab the text from the 3rd p tag

Try:

"//div[@class='container']/div/p[3]"

This should return all third p in all div inside of div with class container.

hr_117
  • 9,589
  • 1
  • 18
  • 23