note 124016 rejected from domdocument.getelementsbytagname by cmb
| From: | cmb@php.net | Date: | Fri, 05 Jul 2019 11:33:25 +0000 |
| Subject: | note 124016 rejected from domdocument.getelementsbytagname by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-211480@lists.php.net to get a copy of this message | ||
Note Submitter: dangtu dot work at gmail dot com
----
Even though the DOMDocument::getElementsByTagName doesn't return null on the no-match-found
case. We can still do this to check whether matched elements found or not:
<?php
$html = <<< HTML
<article id="p73" class="p-quote">
Albert Einsteinâs Quotes Collection
<blockquote><p>Life is like riding a bicycle. To keep your balance, you must keep
moving.</p></blockquote>
<blockquote><p>Pure mathematics is, in its way, the poetry of logical
ideas.</p></blockquote>
<blockquote><p>Education is what remains after one has forgotten what one has learned
in school.</p></blockquote>
<blockquote><p>Learn from yesterday, live for today, hope for tomorrow. The important
thing is not to stop questioning.</p></blockquote>
<blockquote><p>Logic will get you from A to B. Imagination will take you
everywhere.</p></blockquote>
<blockquote><p>If you canât explain it simply, you donât understand it well
enough.</p></blockquote>
<blockquote><p>The difference between stupidity and genius is that genius has its
limits.</p></blockquote>
</article>
HTML;
$doc = new DomDocument();
@$doc->loadHTML($html);
function getSampleTag($tag) {
global $doc;
# Get the first element from the result.
# If no elemet found, it will return DomDocument object.
return $doc->getElementsByTagName($tag)->item(0);
}
$sample = getSampleTag('video');
if ($sample):
echo $doc->saveHTML($sample);
else:
# This is the result due to no <video> was found.
# But I totally have no idea why
echo 'empty';
endif;
?>