我试图运行此代码,但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 attrib,但是不知怎么的,我不知道getAttribute()

最佳答案

必须循环查看getElementsByTagName()的结果
此函数返回一个DomNodeList,getAttribute属于domeElement

//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;
    }
}

关于php - DOMNodeList::getAttribute未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45773079/

10-11 03:32