Получение всех изображений src из определенного div

Предположим, у меня есть такая структура HTML:

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

Я хочу получить все изображения из src .content дела. Я старался :

 <?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, Пожалуйста помоги.

1

Решение

Измените ваш запрос 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"}
4

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector