note 124016 added to domdocument.getelementsbytagname

From: Date: Fri, 05 Jul 2019 09:11:25 +0000
Subject: note 124016 added to domdocument.getelementsbytagname
Groups: php.notes 
Request: Send a blank email to php-notes+get-211479@lists.php.net to get a copy of this message
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; ?> ---- Server IP: 208.43.231.9 Probable Submitter: 119.81.81.244 (proxied: 171.233.190.19) ---- Manual Page -- http://php.net/manual/en/domdocument.getelementsbytagname.php Edit -- https://master.php.net/note/edit/124016 Del: integrated -- https://master.php.net/note/delete/124016/integrated Del: useless -- https://master.php.net/note/delete/124016/useless Del: bad code -- https://master.php.net/note/delete/124016/bad+code Del: spam -- https://master.php.net/note/delete/124016/spam Del: non-english -- https://master.php.net/note/delete/124016/non-english Del: in docs -- https://master.php.net/note/delete/124016/in+docs Del: other reasons-- https://master.php.net/note/delete/124016 Reject -- https://master.php.net/note/reject/124016 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#211479) next »