phphtmlstringdomgetelementsbyclassname

Get ul li a string values and store them in a variable or array php


I'm trying to store the string values of a list item on my website into a variable/array in PHP to do some conditional checks/statements with them. I am having a bit of difficulty getting the list item's string value using PHP. Can anybody help?

This is the markup.

<div class="coursesListed">
<ul>
<li><a href="#"><h3>Item one</h3></a></li>
<li><a href="#"><h3>item two</h3></a></li>
<li><a href="#"><h3>Item three</h3></a></li>            
</ul>
</div>

What I want ideally is either a variable or array that holds the values "Item one", "Item two", "Item three".


Solution

  • Try this

    $html = '<div class="coursesListed">
    <ul>
    <li><a href="#"><h3>Item one</h3></a></li>
    <li><a href="#"><h3>item two</h3></a></li>
    <li><a href="#"><h3>Item three</h3></a></li>            
    </ul>
    </div>';
    
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    $liList = $doc->getElementsByTagName('li');
    $liValues = array();
    foreach ($liList as $li) {
        $liValues[] = $li->nodeValue;
    }
    
    var_dump($liValues);