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

RoseCoder picture RoseCoder · Jul 14, 2013 · Viewed 12k times · Source

Im trying to store the string value's of a list item on my website into a variable/array in PHP to do some conditional checks/statements with them. Am having a bit off 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".

Answer

Manoj Yadav picture Manoj Yadav · Jul 14, 2013

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