Get specific child tag from DOMElement in PHP

I go through the xml definition file and I have a DOMNodeList that I am viewing. I need to extract the contents of a child tag, which may or may not be in the current object

<input id="name"> <label>Full Name:</label> <required /> </input> <input id="phone"> <required /> </input> <input id="email" /> 

I need to replace ?????????????? with something that will deliver me the contents of the tag tag, if one exists.

the code:

 foreach($dom->getElementsByTagName('required') as $required){ $curr = $required->parentNode; $label[$curr->getAttribute('id')] = ????????????? } 

Expected Result:

 Array( ['name'] => "Full Name:" ['phone'] => ) 
+6
dom xml php
source share
1 answer

Strange: you already know the answer, as you use it in the script, getElementsByTagName () .
But this time, not with the DOMDocument as the "node" context, but with the input DOMElement:

 <?php $doc = getDoc(); foreach( $doc->getElementsByTagName('required') as $e ) { $e = $e->parentNode; // this should be the <input> element // all <label> elements that are direct children of this <input> element foreach( $e->getElementsByTagName('label') as $l ) { echo 'label="', $l->nodeValue, "\"\n"; } } function getDoc() { $doc = new DOMDocument; $doc->loadxml('<foo> <input id="name"> <label>Full Name:</label> <required /> </input> <input id="phone"> <required /> </input> <input id="email" /> </foo>'); return $doc; } 

Fingerprints label="Full Name:"

+8
source share

All Articles