2016-02-26 94 views
1

想,我有HTML結構,如:抓取所有圖片來自特定的div SRC

<div> 
     <div class="content"> 
      <p>This is dummy text</p> 
      <p><img src="a.jpg"></p> 
      <p>This is dummy text</p> 
      <p><img src="b.jpg"></p> 
     </div> 
</div> 

我想從.content DIV獲取所有圖片src。我想:

<?php 
// a new dom object 
$dom = new domDocument; 

// load the html into the object 
$dom->loadHTML("example.com/article/2345"); 

// discard white space 
$dom->preserveWhiteSpace = false; 
//get element by class 
$finder = new DomXPath($dom); 
$classname = 'content'; 
$content = $finder->query("//*[contains(@class, '$classname')]"); 
foreach($content as $item){ 
    echo $item->nodevalue; 
} 

但是,我不能當我遍歷$content得到任何東西。請幫忙。

+0

安置自己的循環代碼嗎? – Vincent

+0

是的。我發佈了。 – user254153

+0

我可以看到循環中的虛擬文本位,繼承人 - https://3v4l.org/MXSK7,你確定你從example.com/article/2345獲得的結構與你的樣本結構相同嗎? – Vincent

回答

4

更改您的XPath查詢,如下圖所示:

// loading html content from remote url 
$html = file_get_contents("http://nepalpati.com/entertainment/22577/"); 
@$dom->loadHTML($html); 
... 
$classname = 'content'; 
$img_sources = []; 

// getting all images within div with class "content" 
$content = $finder->query("//div[@class='$classname']/p/img"); 
foreach ($content as $img) { 
    $img_sources[] = $img->getAttribute('src'); 
} 
... 
var_dump($img_sources); 
// the output: 

array(2) { 
    [0]=> 
    string(68) "http://nepalpati.com/mediastorage/images/2072/Falgun/khole-selfi.jpg" 
    [1]=> 
    string(72) "http://nepalpati.com/mediastorage/images/2072/Falgun/khole-hot-selfi.jpg" 
} 
+0

我有一個空數組。 – user254153

+0

@ user254153,哦,是的。只是一點點修復。看一下這個。它應該工作 – RomanPerekhrest

+0

'$ dom-> loadHTML(「example.com/article/2345」); '沒有爲我加載任何html。有什麼問題嗎。 – user254153