图像拉脚本不工作PHP

时间:2016-02-17 12:46:30

标签: php

不确定为什么下面的代码不起作用,它显示了" Else" IF语句中的值基本上说在页面上没有找到IMG标签,但是..我确定它们在那里?任何建议或指导将不胜感激。

    // This variable will contain all the HTML source code of the sample page
$htmlContent = file_get_contents('https://www.instagram.com/ken_flavius/');

var_dump($htmlContent);

// We'll add all the images in this array
$images = [];

// Instantiate a new object of class DOMDocument
$doc = new DOMDocument();

// Load the HTML doc into the object
$doc->loadHTML($htmlContent);

// Get all the IMG tags in the document
$elements = $doc->getElementsByTagName('img');

// If we get at least one result
if($elements->length > 0)
{
    // Loop on all of the IMG tags
    foreach($elements as $element)
    {
        // Get the attribute SRC of the IMG tag (this is the link of the image)
        $src = $element->getAttribute('src');

        if (strlen($src) > 0) {
            // Add the link to the array containing all the links
            array_push($images, $src);
        }

    }

    //show all links
    echo '<pre>'."\r\n";
    print_r($images);
    echo '</pre>'."\r\n";

} else {
    // No result, it means that there were no IMG tags
    echo 'no img tag found in the HTML source provided!';
}

编辑它以显示我正在使用的确切示例。

1 个答案:

答案 0 :(得分:0)

$url="http://example.com"; 
$html = file_get_contents($url);
$doc = new DOMDocument();
@$doc->loadHTML($html);

$tags = $doc->getElementsByTagName('img');

foreach ($tags as $tag) {
   echo $tag->getAttribute('src');
}