Susan Williams
Susan Williams

Reputation: 317

How to get the contents between <li> tag using php?

I am trying to get the content between the <li> tag from an html code i have using php.

the code I have is

 <div class="container">
      <ul class="inside content">
         <li>number 1 </li>
         <li>number 2 </li>
         <li>number 3 </li>
      </ul>

      <ul class="outside content">
         <li class="different class">number 1 </li>
         <li class="different class">number 2 </li>
         <li class="different class">number 3 </li>
      </ul>
 </div>

now i am trying to get the content with the <li> tag of both the <ul> tags separately. So can someone help me out with this.

Upvotes: 1

Views: 1653

Answers (1)

Professor Abronsius
Professor Abronsius

Reputation: 33813

using DOMDocument - untested but the idea is sound

        $strHTML=' <div class="container">
          <ul class="inside content">
             <li>number 1 </li>
             <li>number 2 </li>
             <li>number 3 </li>
          </ul>

          <ul class="outside content">
             <li class="different class">number 1 </li>
             <li class="different class">number 2 </li>
             <li class="different class">number 3 </li>
          </ul>
     </div>';

    $aul1=array();
    $aul2=array();

    $dom=new DOMDocument;
    $dom->loadHTML( $strHTML );/* where $strHTML is the html you wish to parse*/
    $col=$dom->getELementsByTagName('li');

    foreach( $col as $node ) {
        if( $node && $node->parentNode->hasAttribute('class') && $node->parentNode->getAttribute('class')=='inside content' ) $aul1[]=$node->nodeValue;
        if( $node && $node->parentNode->hasAttribute('class') && $node->parentNode->getAttribute('class')=='outside content' ) $aul2[]=$node->nodeValue;
    }

    print_r( $aul1 );
    print_r( $aul2 );

Upvotes: 4

Related Questions