ServerSideSkittles ServerSideSkittles - 14 days ago 6
PHP Question

DOM getElementsByTagName and make an associative array

I m trying to read some html then make an associative array from the results of the 'ul li span' and 'ul li strong'. The span will contain the first value and the strong the second. When I have tried this I get the error

Trying to get property of non-object


My php is

// Start the process of stripping the elements and putting in an assocative array
libxml_use_internal_errors(true);

$dom = new DOMDocument();
$dom->loadHTML($result);


$results = array();

// Get all li elements on the page
foreach ($dom->getElementsByTagName('ul') as $ul) {
$results[$ul->getElementsByTagName('span')->item(0)->textContent]=$ul->getElementsByTagName('strong')->item(1)->textContent;
}


and the html looks as follows

<ul class="ul-data">

<li>
<span>Vehicle make </span>
<strong>AUDI</strong>
</li>


<li id="date">
<span>Date of first registration </span>
<strong>31 March 2005</strong>
</li>a

<li>
<span>Year of manufacture </span>
<strong>1999</strong>
</li>

<li id="cc">
<span>Cylinder capacity (cc) </span>
<strong>2993 cc</strong>
</li>

<li>
<span>COâ‚‚Emissions </span>
<strong id="CO2EmissionShown">142 g/km</strong>
</li>

<li id="fuel">
<span>Fuel type </span>
<strong id="FuelTypeShown">DIESEL</strong>
</li>

<li>
<span>Export marker </span>
<strong>No</strong>
</li>
<li>
<span>Vehicle status </span>
<strong>Tax not due</strong>
</li>
<li>
<span>Vehicle colour </span>
<strong>GREY</strong>
</li>
<li>
<span>Vehicle type approval </span>
<strong>M1</strong>
</li>

<li>
<span>Wheelplan </span>
<strong>2 AXLE RIGID BODY</strong>
</li>

<li>
<span>Revenue weight </span>
<strong>Not available</strong>
</li>

</ul>


As you can see the span is the title and the strong is the value. In Jquery I could just do $('ul span'); and $('ul strong'); Am I right in looping the li's through and then selecting them? I know somehow this is wrong but I am not sure how to approach after trying other methods such as fetching both separately but im not sure how to do this using DOM.

Answer

There's only a single <ul>, and the <strong> you're looking for is item(0).

foreach ($dom->getElementsByTagName('li') as $li) {
    $key = $li->getElementsByTagName('span')->item(0)->textContent;
    $value = $li->getElementsByTagName('strong')->item(0)->textContent;
    $results[trim($key)] = trim($value);
}