2016-11-24 112 views
0

我試圖讀取一些html,然後從'ul li span'和'ul li strong'的結果中創建一個關聯數組。跨度將包含第一個值,強度則包含第二個值。當我嘗試這樣做,我得到了錯誤DOM getElementsByTagName並創建關聯數組

Trying to get property of non-object 

我的PHP是

// 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; 
} 

和HTML如下所示

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

正如你所看到的跨度是標題和價值很強。在JQuery中我可以做$('ul span');和$('ul strong');我是否正確地循環播放,然後選擇它們?我知道不知怎麼這是錯誤的,但我不知道如何嘗試其他方法後,如單獨提取,但我不知道如何使用DOM做到這一點。

回答

3

只有一個<ul>,而您要找的<strong>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); 
} 
0

在你的循環中,你應該通過李的不是一個ul。

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