1
votes

I want to get img src from RSS feed, but I only need image inside <div class="img" not any other class="favicon" img src. But when I get image it's not the original image but it's returning the favicon. How can I fix it? Here is the feed link "http://rss.disp.cc/PttHot.xml" . And here is my code:

   <?php 
    $ptt = simplexml_load_file('http://rss.disp.cc/PttHot.xml');
    foreach ($ptt->entry as $entry ) {
    $content  = $entry -> content;
    preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $content, $images);
   if(!empty($images)){$img = $images[1];}else{$img="";}?>

I am trying to get image from content and here is multiple img src inside content but I only need original image inside <div class="image"> and img style="max-width:100%;" not other extra favicon. Please help - I tried multiple solutions but I can't fix.

1

1 Answers

0
votes

Maybe you could use an xpath expression instead of a regex using DOMDocument.

The $entry->content contains html so you could load that with loadHTML.

Then you could use an xpath expression to get the img tags:

//div[contains(@class, 'img')]/img[contains(@style, 'max-width:100%') and not(contains(@class,'favicon'))]

For example:

$ptt = simplexml_load_file('http://rss.disp.cc/PttHot.xml');
$doc = new DOMDocument();
foreach ($ptt->entry as $entry) {
    $internalErrors = libxml_use_internal_errors(true);
    $doc->loadHTML((string)$entry->content);
    libxml_use_internal_errors($internalErrors);
    $xpath = new DOMXpath($doc);
    $items = $xpath->query("//div[contains(@class, 'img')]/img[contains(@style, 'max-width:100%') and not(contains(@class,'favicon'))]");
    foreach ($items as $item) {
        $img = $item->getAttribute('src');
        echo $img . "<br>";
    }
}