如何在这个img标签中获取src attr

时间:2014-05-22 23:38:20

标签: php html parsing dom simple-html-dom

我正在使用PHP简单的HTML DOM解析器和everithing运行正常,直到我得到这个div内容。我已经尝试了各种方法来获取src attr,找到一个标签,img,并且全部失败,我可以得到img标签,但只能获得宽度,高度和alt attr(只是“一些”的部分文字“出现,而不是其他字符串。”

<img width="656" height="370" 
alt="some text " .="" othertetx="" anothertext="" anothertext="" anothertext="" anothertext'="" title="same text in the alt attr " src="http://siteurl/getattach/somedir/somefile.aspx">

我认为问题出现在alt attr中,所有带有。=符号的文本都会混淆解析器。此标记在浏览器中显示正常,因此,它必须是“标准”

编辑:

答案指出并没有解决问题,我知道如何获得src,问题在于这个标签。请花时间完整阅读问题,然后再将其标记为重复。在sugested答案中提供的代码不适用于我展示的样本。

这个

$img_src = $element->src;
if(!strstr($img_src, 'http://')) {
    $img_src = $v . $img_src;
}

不要从此

中提取src attr
<img width="656" height="370" 
    alt="some text " .="" othertetx="" anothertext="" anothertext="" anothertext="" anothertext'="" title="same text in the alt attr " src="http://siteurl/getattach/somedir/somefile.aspx">

1 个答案:

答案 0 :(得分:0)

<img>元素无效HTML。它显示了属性声明的几个问题。我建议使用像W3C online validator这样的验证服务来查看这些错误。我已将您问题中的img标记包装到this document进行验证。

但是,虽然<img>标记无效,但DOMDocument类能够解析它。像这样:

$string = <<<EOF
<img width="656" height="370"
alt="some text " .="" othertetx="" anothertext="" anothertext="" anothertext="" anothertext'="" title="same text in the alt attr " src="http://siteurl/getattach/somedir/somefile.aspx">
EOF;

$doc = new DOMDocument();
@$doc->loadHTML($string);

$images = $doc->getElementsByTagName('img');
echo $images->item(0)->getAttribute('src');

输出:

http://siteurl/getattach/somedir/somefile.aspx

请注意,simplehtmldom类不如内置DOM扩展程序强大。它是在PHP没有内置DOM扩展名的时候编写的。在大多数情况下,现在可以考虑弃用它。

相关问题