用PHP获取img src [英] Get img src with PHP

查看:109
本文介绍了用PHP获取img src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < img border =0我想在这个例子中将SRC属性变成一个变量: src =/ images / image.jpgalt =Imagewidth =100height =100/> 

例如 - 我想获得一个变量 $ foo = /images/image.jpg
重要! src属性将是动态的,所以它不能被硬编码。
有没有什么快捷的方法可以做到这一点?

谢谢!

编辑:The图像将成为一个巨大的字符串的一部分,基本上是新闻报道的内容。所以图像只是其中的一部分。



编辑2:这个字符串中会有更多的图像,我只想得到第一个图像的src。这可能吗?

解决方案

使用HTML解析器,如 DOMDocument ,然后使用 DOMXpath 评估您要查找的值:

  $ html ='< img id =12border =0src =/ images / image.jpg
alt =Imagewidth =100height =100/>';

$ doc = new DOMDocument();
$ doc-> loadHTML($ html);
$ xpath = new DOMXPath($ doc);
$ src = $ xpath-> evaluate(string(// img / @ src)); #/images/image.jpg

或者对于那些真正需要节省空间的人:

  $ xpath = new DOMXPath(@DOMDocument :: loadHTML($ html)); 
$ src = $ xpath-> evaluate(string(// img / @ src));

对于单线队员来说:

  $ src =(string)reset(simplexml_import_dom(DOMDocument :: loadHTML($ html)) - > xpath(// img / @ src)); 


I would like to get the SRC attribute into a variable in this example:

<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />

So for example - I would like to get a variable $foo = "/images/image.jpg". Important! The src attribute will be dynamic, so it mustn't be hardcoded. Is there any quick and easy way to do this?

Thanks!

EDIT: The image will be a part of a huge string that is basically the content of a news story. So the image is just a part of that.

EDIT2: There will be more images in this string, and I would only want to get the src of the first one. Is this possible?

解决方案

Use a HTML parser like DOMDocument and then evaluate the value you're looking for with DOMXpath:

$html = '<img id="12" border="0" src="/images/image.jpg"
         alt="Image" width="100" height="100" />';

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/@src)"); # "/images/image.jpg"

Or for those who really need to save space:

$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/@src)");

And for the one-liners out there:

$src = (string) reset(simplexml_import_dom(DOMDocument::loadHTML($html))->xpath("//img/@src"));

这篇关于用PHP获取img src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆