DOMNodeList :: getAttribute未定义

时间:2017-08-19 15:08:00

标签: php html dom html-table

我试着运行这段代码,但是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>
&#13;
&#13;
&#13;

然后我把它叫到这个文件

&#13;
&#13;
//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;
&#13;
&#13;
&#13; 很明显,我想从它获得src attrib,但不知何故无法识别getAttribute()

1 个答案:

答案 0 :(得分:0)

您必须遍历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;
    }
}