2017-08-12 16 views
0

domxpathを使ってimg srcの値を取得したいと思います。PHPのdomxpathを使ってimg srcを取得する方法

私たちは、私がこのsample.htmlページを持っているとしましょう:

CURL、のDOMDocumentとDOMXPathを使うことの最大を使用して
<div id="wrapper"> 
    <div class="item"> 
     <div class="img-wrapper"> 
      <img src="sample1.jpg"/> 
      <p class="title">Sample 1</p> 
     </div> 
    </div> 
    <div class="item"> 
     <div class="img-wrapper"> 
      <img src="sample2.jpg"/> 
      <p class="title">Sample 2</p> 
     </div> 
    </div> 
    <div class="item"> 
     <div class="img-wrapper"> 
      <img src="sample3.jpg"/> 
      <p class="title">Sample 3</p> 
     </div> 
    </div> 
</div> 

私はのimg srcとタイトルを取得したい:

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, 'http://path/to/sample.html'); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
$result = curl_exec($ch); 
curl_close($ch); 

$dom = new DOMDocument(); 
$dom->loadHTML($result); 
$xpath = new DOMXPath($dom); 
$entries = $xpath->query('//div[@id="wrapper"]/div[@class="item"]'); 
$results = array(); 
foreach ($entries as $entry) { 
    $result = array(); 
    $result['img'] = $xpath->query("img", $entry)->item(0)->nodeValue; 
    $result['title'] = $xpath->query("p[@class='title']", $entry)->item(0)->nodeValue; 
    $results[] = $result; 
} 
return $results; 

これは、になりますimg as null:

[ 
    { 
     "img": null, 
     "title": "Sample 1" 
    }, 
    { 
     "img": null, 
     "title": "Sample 2" 
    }, 
    { 
     "img": null, 
     "title": "Sample 3" 
    } 
] 

img srcの値を取得する方法を教えてください。ありがとうございました!

答えて

2

値をフェッチであなたのXPathを使用すると、属性を取得方法は@attibuteNameを使用することです...

$result['img'] = $xpath->query("//img/@src", $entry)[0]->value; 
$result['title'] = $xpath->query("//p[@class='title']", $entry)[0]->nodeValue; 

注意する必要があり、非常に正確ではありません。また、最初に//を指定すると、XPathは開始点の下の任意のポイントで要素を見つけることができます。

+0

woowを使用し、あなたの例では、ここでの方法getAttribute('attribute_name')

を使用して、任意のDOM要素の属性を取得することができます。 。ありがとうございます。それは動作します:D – JSmith

1

あなたはgetAttribute('src')

$result['img'] = $xpath->query("//img", $entry)->item(0)->getAttribute('src'); 
$result['title'] = $xpath->query("//p[@class='title']", $entry)->item(0)->nodeValue; 
+0

おかげで仲間。それも動作します – JSmith

関連する問題