2017-09-13 147 views
1

如何使用php簡單的html dom獲取href裏面的「name」或「id」屬性。另外我需要「標題文本」在「h4」標籤內。 你能幫我嗎? 下面是HTML:php簡單的html dom獲取td內的href id

<td> 
<a href="../Vehicle?itemID=22995061&RowNumber=9&loadRecent=True" name="22995061" id="22995061"> 
<h4>title text</h4> 
</a> 
<p> 
Stock#: 
<text>example</text> 
</p> 
<p>BLA BLA</p> 
<p> fffff </p> 
</td> 

我想這樣的事情,但它返回我的空白。

IDs = array(); 
    $url = "http://someurl"; 
    $html = file_get_html(url); 
foreach($html->find('h4') as $e) 
{ 

    echo $e->innertext."<br>"; 
    $dataID = $e->innertext; 
    $IDs[] = $dataID; 

} 

回答

0

首先,變化,

IDs = array(); 

到,

$IDs = array(); 

那麼,你爲什麼不利用DOMDocument類的,而不是一個正則表達式。只需加載您的DOM,然後使用getElementsByTagName來獲取您的標籤。通過這種方式,您可以排除任何您不需要的其他標籤,只會獲得您所需的標籤。

<?php 
$xml = <<< XML 
<?xml version="1.0" encoding="utf-8"?> 
<books> 
<book>Patterns of Enterprise Application Architecture</book> 
<book>Design Patterns: Elements of Reusable Software Design</book> 
<book>Clean Code</book> 
</books> 
XML; 

$dom = new DOMDocument; 
$dom->loadXML($xml); 
$books = $dom->getElementsByTagName('book'); 
foreach ($books as $book) { 
    echo $book->nodeValue, PHP_EOL; 
} 
?> 

閱讀材料

DOMDocument

+0

嗨,TNX的答覆,但我使用PHP簡單的HTML DOM搶數據,因爲我是我代理後面。當我在代理服務器後面時,我不知道如何使用php DOM來獲取URL。 – dilesko