Php 使用新的DOMDocument()获取第一个图像
我正在尝试获取一些HTML的第一个图像。我知道如何使用for循环实现所有图像。然而,我正在努力获得第一个 我有以下代码:Php 使用新的DOMDocument()获取第一个图像,php,dom,Php,Dom,我正在尝试获取一些HTML的第一个图像。我知道如何使用for循环实现所有图像。然而,我正在努力获得第一个 我有以下代码: function get_first_image_b() { global $post, $posts; ob_start(); ob_end_clean(); $html= $post->post_content; $doc = new DOMDocument(); @$doc->loadHTML($html)
function get_first_image_b() {
global $post, $posts;
ob_start();
ob_end_clean();
$html= $post->post_content;
$doc = new DOMDocument();
@$doc->loadHTML($html);
$img = $doc->getElementsByTagName('img');
print_r($img);
}
它吐出:
(
[length] => 4
)
有人知道我如何将第一个项目转换为字符串/或可用的内容吗?尝试使用
项
方法:
echo $img->item(0)->getAttribute('src');
尝试使用
项
方法:
echo $img->item(0)->getAttribute('src');
domandelist
对象实现了可遍历,因此您可以这样做
$img = $doc->getElementsByTagName('img');
$first_image = $img->current(); // get first element in list
domandelist
对象实现了可遍历,因此您可以这样做
$img = $doc->getElementsByTagName('img');
$first_image = $img->current(); // get first element in list
@t这是由于回声引起的。如果您想查看实际的对象信息,只需使用
var\u dump($img->item(0))
!你是如何从:doElement对象([tagName]=>img[schemaTypeInfo]=>[nodeName]=>img[nodeValue]=>[nodeType]=>1[parentNode]=>(省略对象值)[childNodes]=>(省略对象值)[firstChild]=>[lastChild]=>[previousSibling]=>[attributes]=>(省略对象值)[ownerDocument]=>(省略对象值)得到的[namespaceURI]=>[prefix]=>[localName]=>img[baseURI]=>[textContent]=>)
?DoElement::getAttribute。它扩展了DOMNode。@tmyie这是因为echo
。如果您想查看实际的对象信息,只需使用var\u dump($img->item(0))
!你是如何从:doElement对象([tagName]=>img[schemaTypeInfo]=>[nodeName]=>img[nodeValue]=>[nodeType]=>1[parentNode]=>(省略对象值)[childNodes]=>(省略对象值)[firstChild]=>[lastChild]=>[previousSibling]=>[attributes]=>(省略对象值)[ownerDocument]=>(省略对象值)得到的[namespaceURI]=>[prefix]=>[localName]=>img[baseURI]=>[textContent]=>)
?DoElement::getAttribute。它扩展了DOMNode。$img=$doc->getElementsByTagName('img')$第一个图像=$img->current();//获取列表echo$first_图像中的第一个元素代码>也会产生错误。“DomeElement类的对象无法转换为字符串”@tmyie不echo
it。它是一个物体。出现错误的原因是该对象必须没有实现\uu toString()
。$img=$doc->getElementsByTagName('img')$第一个图像=$img->current();//获取列表echo$first_图像中的第一个元素代码>也会产生错误。“DomeElement类的对象无法转换为字符串”@tmyie不echo
it。它是一个物体。出现错误的原因是该对象必须没有实现\uu toString()
。