DOMNodeList::getAttribute 未定义

Posted

技术标签:

【中文标题】DOMNodeList::getAttribute 未定义【英文标题】:DOMNodeList::getAttribute is undefined 【发布时间】:2018-01-28 02:38:31 【问题描述】:

我尝试运行此代码,但 php 抛出:致命错误:调用 path/to/feature-manager.php 中未定义的方法 DOMNodeList::getAttribute()

此文件包含 html

//features.php

<div class="col-md-4">
  <div class="feature">
 <img class="img-fluid" src="media/artwork_icon_512.png" id="feature-icon1">
  <h4>Feature 1</h4>
    </div>
</div><!---->
    
    
<div class="col-md-4">
  <div class="feature">
 <img class="img-fluid" src="media/dress_flat_icon-512.png" id="feature-icon2">
  <h4>Feature 2</h4>
    </div>
</div><!---->
    
   
<div class="col-md-4">
  <div class="feature">
  <img class="img-fluid" src="media/users-512.png" id="feature-icon3">
  <h4>Feature 3</h4>
    </div>
</div>

然后我把它调用到这个文件中

//feature-manager.php

$read=file_get_contents('../include/features.php');
$features = explode('<!---->', $read);

$doc= new DOMDocument();
foreach ($features as $feature) 
	
$doc->loadHTML($feature);
$img = $doc->getElementsByTagName("img"); 
	$imgsrc = $img->getAttribute('src');
	
echo $imgsrc;
显然我想从中获取 src 属性,但不知何故无法识别 getAttribute()

【问题讨论】:

【参考方案1】:

你必须遍历getElementsByTagName()的结果

这个函数返回一个DomNodeList,getAttribute属于DOMElement

//feature-manager.php

$read=file_get_contents('../include/features.php');
$features = explode('<!---->', $read);

$doc= new DOMDocument();
foreach ($features as $feature) 
	
    $doc->loadHTML($feature);
    $images = $doc->getElementsByTagName("img"); 
    foreach($images as $img)

	    $imgsrc = $img->getAttribute('src');
	    echo $imgsrc;
    

【讨论】:

以上是关于DOMNodeList::getAttribute 未定义的主要内容,如果未能解决你的问题,请参考以下文章