Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DOM elements by tag name with DOMDocument::loadHTML and getElementsByTagName

Sorry if this is reposted, but I can't wrap my mind around it and I've tried all the available documentation and examples I could find.

I am trying to get the first img element of a string containing HTML

PHP

$html = '<p><img src="http://placekitten.com/200/300" alt="" width="200" height="300" /></p>';
$dom = new DOMDocument;
$dom->loadHTML($html);
$imgs = $dom->getElementsByTagName('img');
var_dump($imgs);

This spits object(DOMNodeList)#57 (0) { } when it should find the one occurrence.

I've tried with XPath with no luck either.

like image 276
Naoise Golden Avatar asked Jul 20 '12 00:07

Naoise Golden


People also ask

How do I select an element by tag name?

Get Element(s) By Tag Name Using getElementsByTagName() Call the getElementsByTagName() on the global document object. The getElementsByTagName() method takes one argument which is the tag name. It gets all div elements from the entire document and returns an array-like object called HTMLCollection.

How to get element by name in PHP?

The DOMElement::getElementsByTagName() function is an inbuilt function in PHP which is used to get the elements by tagname. Parameters: This function accepts a single parameter $name which holds the tag name or use * for getting all the tags.

How to get elements by id in PHP?

The DOMDocument::getElementById() function is an inbuilt function in PHP which is used to search for an element with a certain id. Parameters:This function accepts a single parameter $elementId which holds the id to search for. Return Value: This function returns the DOMElement or NULL if the element is not found.

What is getElementsByTagName in Javascript?

Definition and Usage The getElementsByTagName() method returns a collection of all elements with a specified tag name. The getElementsByTagName() method returns an HTMLCollection. The getElementsByTagName() property is read-only.


1 Answers

The correct answer has already been provided by @nickb but you can also do the same without having to use getNamedItem() in the second line of the code provided by @nickb, like this:

echo $img->attributes->src->value;

NOTE: I wanted to add the above code as a comment to @nickb's answer, but I need a minimum of 50 reputations to do that. If anyone can write the above code line as a comment to @nickb's answer, please let me know. I will then delete my answer.

like image 114
Uzair Zia Avatar answered Sep 21 '22 19:09

Uzair Zia