gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:45:46 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com