0

I am trying to retrieve and parse RSS feed using cURL and SimpleXML. Some of the items does not contain thumbnail $item->featuredImage->img['src'] so I want to display simple message (No File) to those items which does not contain any thumbnail but it is not working as expected.

$thubmnail returns full path to the file.

but

if (!file_exists($thubmnail)) {
        echo '<img src="' . $item->featuredImage->img['src'] . '" width="100" height="100" alt="' . $item->title . '" class="' . $item->featuredImage->img['class'] . '">';
      } else {
        echo "No File";
      }

fails to check the file and display empty image.

Here is how my entire code looks:

<?php
$curl = curl_init();
curl_setopt_array($curl, Array(
  CURLOPT_URL            => 'http://domain.com/blog/index.php/feed/',
  CURLOPT_USERAGENT      => 'spider',
  CURLOPT_TIMEOUT        => 120,
  CURLOPT_CONNECTTIMEOUT => 30,
  CURLOPT_RETURNTRANSFER => TRUE,
  CURLOPT_ENCODING       => 'UTF-8'
));
$data = curl_exec($curl);
curl_close($curl);
$xml = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
//die('<pre>' . print_r($xml], TRUE) . '</pre>');
?>
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body>

<ul>
  <?php foreach ($xml->channel->item as $item) {
    $creator = $item->children('dc', TRUE);
    $thubmnail = $item->featuredImage->img['src'];
    echo '<li class="news-item">';
      if (!file_exists($thubmnail)) {
        echo '<img src="' . $item->featuredImage->img['src'] . '" width="100" height="100" alt="' . $item->title . '" class="' . $item->featuredImage->img['class'] . '">';
      } else {
        echo "No File";
      }
      echo '<h2>' . $item->title . '</h2>';
      echo '<p>Created: ' . $item->pubDate . '</p>';
      echo '<p>Author: ' . $creator . '</p>';
      echo '<p>' . $item->description . '</p>';
      echo '<p><a href="' . $item->link . '">Read more</a></p>';
    echo '</li>';
  }
  ?>
</ul>
Kevin S
  • 11
  • 7
  • What is the value `$thubmnail` contains. Is it a url or a file directory path. – Haridarshan Oct 22 '16 at 09:15
  • @haridarshan `echo $thubmnail` will output `http://domain.com/blog/wp-content/uploads/2016/10/3.png` – Kevin S Oct 22 '16 at 09:26
  • Since `$thumbnail` contains url, file_exists will not work. To check remote urls/paths, you can refer this http://stackoverflow.com/questions/15477232/how-to-check-url-image-is-exist-or-not-in-php – Haridarshan Oct 22 '16 at 09:27

0 Answers0