Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/amazon-web-services/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何从URL获取图像链接_Php_Html_Image_Domdocument_File Get Contents - Fatal编程技术网

Php 如何从URL获取图像链接

Php 如何从URL获取图像链接,php,html,image,domdocument,file-get-contents,Php,Html,Image,Domdocument,File Get Contents,如何使用file\u get\u contents访问网页,并获取显示在网页上的图像链接 在页面上,这行代码导致显示图像: <img class='' src='https://t0.rbxcdn.com/5d4449ed656bd92c4d51805ff8b72610' /> 您可以使用getAttribute(“src”),即: $dom = new DOMDocument(); $html = file_get_contents('https://www.roblox.com

如何使用
file\u get\u contents
访问网页,并获取显示在网页上的图像链接

在页面上,这行代码导致显示图像:

<img class='' src='https://t0.rbxcdn.com/5d4449ed656bd92c4d51805ff8b72610' />

您可以使用
getAttribute(“src”)
,即:

$dom = new DOMDocument();
$html = file_get_contents('https://www.roblox.com/thumbnail/asset?assetId=169454280&thumbnailFormatId=254');
$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$imgs =  $dom->getElementsByTagName('img');
foreach($imgs as $img)
{
    print $img->getAttribute("src");
}
如果页面上有多个图像,则可以使用:


根据OP评论更新

如果您确定每页只有一张图像,则可以删除
foreach
循环并使用:

print $imgs[0]->getAttribute("src");

我讨厌这种情况,但有些链接实际上不是图像文件。如果URL不是以.png.gif等文件扩展名结尾

(例如,以.png结尾)


如果您发现以文件扩展名结尾的图像相同,则可能会解决此问题。

我已循环数组以解决此问题,谢谢您指出此问题。谢谢您的回答。页面上只会有一张图片,我可以确认总是会有一张。很酷,我删除了我的重复投票,因为你的答案是正确的complete@TheCodesee我将发布一个更新代码以仅获取一个图像。@PedroLobito我收到了以下错误:
致命错误:无法将DOMNodeList类型的对象用作数组
print $imgs[0]->getAttribute("src");