我使用PHP简单的HTML DOM解析器和一切运行良好,直到我得到这个div内容。我已经尝试了各种方法来获得src attr,找到a标签,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混淆了解析器。这个标签在浏览器中显示得很好,所以,它必须是"standard"
编辑:答案指向不解决问题,我知道如何获得src,问题是与这个标签。在把问题标记为重复之前,请花点时间通读一遍。建议答案中提供的代码不适用于我展示的示例。
$img_src = $element->src;
if(!strstr($img_src, 'http://')) {
$img_src = $v . $img_src;
}
不要从
中提取SRC属性<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">
<img>
元素不是有效的HTML。它显示了属性声明的几个问题。我建议使用像W3C在线验证器这样的验证服务来查看这些错误。我已经将您的问题中的img标签包装到此文档中以进行验证。
然而,虽然<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
扩展的时候编写的。在大多数情况下,它的用法现在可以被认为是过时的。