Reputation: 651
How do I check to see if the 'li
' element has a 'star
' element inside it, and also get the count of the star elements?
<random>
<li>
Blah blah <star item="1"/> blah <star item="2"/> Blah blah blah
</li>
<li>
Blah blah Blah blah blah
</li>
</random>
I'm currently using the following code to select one 'li' element ($liToProcess
) at random. The 'star' check should happen after one li is selected.
$dom = new DOMDocument;
$dom->loadXML($ul);
$liElements = $dom->getElementsByTagName('li');
$liCount = $dom->getElementsByTagName('li')->length;
// Select a random li
$useThisItem = rand(0, $liCount-1);
$liToProcess = $liElements->item($useThisItem)->nodeValue;
// This echo will output 'Blah blah blah Blah blah blah' (if first li is selected)
echo "li: " . $liToProcess;
Upvotes: 1
Views: 175
Reputation: 2768
Try this..
$dom = new DOMDocument;
$dom->loadXML($ul);
$liElements = $dom->getElementsByTagName('li');
$liCount = $dom->getElementsByTagName('li')->length;
// Select a random li
$useThisItem = rand(0, $liCount-1);
$liToProcess = $liElements->item($useThisItem)->nodeValue;
// This echo will output 'Blah blah blah Blah blah blah' (if first li is selected)
echo $liElements->item($useThisItem)->childNodes->length . "<br>";
$noStars = 0;
if($liElements->item($useThisItem)->childNodes->length > 1) {
foreach($liElements->item($useThisItem)->childNodes as $cN) {
if(isset($cN->tagName) && ($cN->tagName === "star") ){
// echo $cN->tagName . "<br/>";
$noStars++;
}
}
}
echo "li: " . $liToProcess . "<br/>\n";
echo "No of Stars = $noStars <br/>\n";
Upvotes: 1