我试图在这里解决一些关于 preg_match 和 DOM 的问题,但一切都在我脑海中浮现。
我有这样一个字符串:
$string = '<td class="borderClass" width="225" style="border-width: 0 1px 0 0;" valign="top">
<div style="text-align: center;">
<a href="http://myanimelist.net/anime/10800/Chihayafuru/pic&pid=35749">
<img src="http://cdn.myanimelist.net/images/anime/3/35749.jpg" alt="Chihayafuru" align="center">
</a>
</div>';
我现在正试图从中获取图像 src 属性值。我尝试使用此代码,但无法弄清楚我做错了什么。
$doc = new DOMDocument();
$dom->loadXML( $string );
$imgs = $dom->query("//img");
for ($i=0; $i < $imgs->length; $i++) {
$img = $imgs->item($i);
$src = $img->getAttribute("src");
}
$scraped_img = $src;
我如何使用 php 从中获取图像 src 属性?
最佳答案
这是更正后的代码,您可以使用:
$string = '<td class="borderClass" width="225" style="border-width: 0 1px 0 0;" valign="top">
<div style="text-align: center;">
<a href="http://myanimelist.net/anime/10800/Chihayafuru/pic&pid=35749">
<img src="http://cdn.myanimelist.net/images/anime/3/35749.jpg" alt="Chihayafuru" align="center">
</a>
</div>';
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML( $string );
$xpath = new DOMXPath($doc);
$imgs = $xpath->query("//img");
for ($i=0; $i < $imgs->length; $i++) {
$img = $imgs->item($i);
$src = $img->getAttribute("src");
}
echo $src;
输出
http://cdn.myanimelist.net/images/anime/3/35749.jpg
关于php - 如何从php字符串中获取图片src属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19323324/