php - 如何从php字符串中获取图片src属性值?

标签 php

我试图在这里解决一些关于 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/

相关文章:

php - 如何在 PHP 中读取交错 XML 的子项

php - 带左连接的 Mysql 查询 - 如果两行相同则专用索引

php - Eloquent Query 用于获取用户没有完成交易的所有用户失败交易

php - Silex Controller 上的构造函数注入(inject)

php - 使用 FormData 对象,服务器收到一个空的 POST

php - Symfony2 - SonataAdmin - 空 admin_list block

php - MySQL根据两列选择前五个唯一行

php - Mailgun Cc header 问题

PHP PDO 未正确绑定(bind)

php - 获取 2 个数组之间的差异