Why is my file_get_contents function resulting in broken images when I try to echo in html?

105 views Asked by At

My function uses file_get_contents and I'm using it to get image src URLs from web pages and then print those images onto a different php/html page. But sometimes images are rendering correctly and sometimes not. Here is my code:

//function to get the contents from a URL
function getSiteOG( $functionurl, $specificTags=0 ){
        $doc = new DOMDocument();
        @$doc->loadHTML(file_get_contents($functionurl));
        $res['title'] = $doc->getElementsByTagName('title')->item(0)->nodeValue;
        foreach ($doc->getElementsByTagName('meta') as $m){
               $tag = $m->getAttribute('name') ?: $m->getAttribute('property');
                            if(in_array($tag,['description','keywords']) || strpos($tag,'og:')===0) $res[str_replace('og:','',$tag)] = $m->getAttribute('content');
                        }
                        return $specificTags? array_intersect_key( $res, array_flip($specificTags) ) : $res;
                    }   

//use function on a variety of URLs passed through $url_db variable
$og_details = getSiteOG($url_db);

//echo image onto page
echo "<img class='preview_image_file image-fit-img' src='".@$og_details['image']."'  alt='Preview image'>";

Sometimes when I pass a URL through the $url_db variable and echo the image onto another page (as shown in the last line of code above), it works fine and displays the image, but sometimes it results in a "broken image" icon

Example URL where is renders the image correctly: https://simplifaster.com/

Example URL where it shows a broken image: https://store.simplifaster.com/

0

There are 0 answers