2013-01-10 52 views
0

我有一个HTML块这里:如何使用PHP DOMDocument解析HTML?

<div class="title"> 
    <a href="http://test.com/asus_rt-n53/p195257/"> 
     Asus RT-N53 
    </a> 
</div> 
<table> 
    <tbody> 
     <tr> 
      <td class="price-status"> 
       <div class="status"> 
        <span class="available">Yes</span> 
       </div> 
       <div name="price" class="price"> 
        <div class="uah">758<span> ua.</span></div> 
        <div class="usd">$&nbsp;62</div> 
       </div> 

如何解析链接(http://test.com/asus_rt-n53/p195257/),标题(Asus RT-N53)和价格(758)?

卷曲代码在这里:

$dom = new DOMDocument(); 
$dom->preserveWhiteSpace = false; 
$dom->loadHTML($content); 
$xpath = new DOMXPath($dom); 
$models = $xpath->query('//div[@class="title"]/a'); 
foreach ($models as $model) { 
    echo $model->nodeValue; 
    $prices = $xpath->query('//div[@class="uah"]'); 
    foreach ($prices as $price) { 
     echo $price->nodeValue; 
    } 
} 
+1

什么是与您当前密码的问题? –

+0

所以我得到一个名称和价格,但我需要更多和一个链接。而且页面上的这些单位并不多,因为它可以在一个循环中执行? 而现在看起来像 杂牌 -Price - ....... -Price ,这是必要的: -Name -Price 连杆式 – Dima

+1

您必须阅读'href'属性。也许这有助于:http://stackoverflow.com/questions/6856668/domdocument-read-tag-attributes-classes。 –

回答

0

一个丑陋的解决方案是投价结果只保留数字:

echo (int) $price->nodeValue; 

或者,您可以查询到找到DIV中的跨度,和从价格上取下(价格的foreach内):

$span = $xpath->query('//div[@class="uah"]/span')->item(0); 
$price->removeChild($span); 
echo $price->nodeValue; 

编辑:

要检索的链接,只需使用getAttribute()并得到href一个:

$model->getAttribute('href') 
+0

与一切的价格是好的,但如何获得链接? Dima

+0

非常感谢! – Dima