Reputation: 275
I have a PHP script that is supposed to read an HTML file and then return the contents of the first <h1>
tag that it finds. I do not want to use regex or the Simple HTML DOM Parser please - just plain, easy PHP.
This is my code thus far:
$document = new DOMDocument();
$document->loadHTMLFile($post_url);
$matches = $document->getElementsByTagName('h1');
$first_h1 = $matches->item(0);
echo $first_h1;
However, when I run the code, I get an error that says PHP Catchable fatal error: Object of class DOMElement could not be converted to string
Can anyone help me with where I am going wrong?
Thanks in advance!
SOLUTION: Replacing the last line with echo $first_h1->nodeValue;
seems to do the trick.
Upvotes: 0
Views: 43
Reputation: 136
You can also get the entire tag value with C14N method of the DOMNode class:
echo $first_h1->C14N();
https://www.php.net/manual/en/domnode.c14n.php
Upvotes: 0
Reputation: 19635
The issue is that $first_h1
is a DOMElement
object rather than a string, and it has no method to convert itself to a string, so you cannot simply echo it out. You can, however do a var_dump
on it:
$document = new DOMDocument();
$document->loadHTMLFile($post_url);
$matches = $document->getElementsByTagName('h1');
$first_h1 = $matches->item(0);
var_dump($first_h1);
If you need to get the text contents of the element (i.e. the text between the tags), use the nodeValue property:
echo $first_h1->nodeValue;
Upvotes: 1
Reputation: 355
$document is an object which can not be converted to string (some objects can).
See this link for all properties and methods it has to offer, e.g.
echo $document->tagName;
or
echo $document->textContent;
Upvotes: 0