How do I get the src attribute of img tags?

天涯浪子 提交于 2019-12-23 17:09:03

问题


I load the DOM by an external url as such:

$dom = new DOMDocument;
$dom->loadHTMLFile( "external_url.html" );

$arrayOfSources = array();

foreach( $dom->getElementsByTagName( "img" ) as $image )
    $arrayOfSources[] = $image->item(0)->getAttribute("src");

This way I want to store all the src attributes of the img tags in an array, but I keep getting the error Fatal error: Call to undefined method DOMDocument::item()

What am I missing here? How do I extract all the src attributes from the img tags in an html?


回答1:


Drop the ->item(0) part.





回答2:


Inside that loop, you don't need to access the element with item(0).

The iterator for that collection allows you to just do a foreach() on it and have it implicitly access each element in the DOMNodeList.




回答3:


Try:

$arrayOfSources[] = $image->getAttribute("src");


来源:https://stackoverflow.com/questions/6441448/how-do-i-get-the-src-attribute-of-img-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!