ServerSideSkittles ServerSideSkittles - 1 year ago 147
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

$dom = new DOMDocument();

$results = array();

// Get all li elements on the page
foreach ($dom->getElementsByTagName('ul') as $ul) {

and the html looks as follows

<ul class="ul-data">

<span>Vehicle make </span>

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

<span>Year of manufacture </span>

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

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

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

<span>Export marker </span>
<span>Vehicle status </span>
<strong>Tax not due</strong>
<span>Vehicle colour </span>
<span>Vehicle type approval </span>

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

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


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 Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download