PHP DOM html get element from another element -
i trying create php html dom work element path pattern.
it looks fallow. can have different paths want have text out. like;
$elements = 'h1;span;'; $elements = 'div.test;h2;span';
i tried create function handle these inserts stuck on part set 'getelementsbytagname()' in order , receive value of last element,
what have done now;
function convertname($html, $elements) { $elements = explode(';', $elements); $dom = new domdocument; $dom->loadhtml($html); $name = null; foreach ($elements $element) : $name. = getelementsbytagname($element)->item(0)->; endforeach; $test = $dom->$name.'nodevalue'; print_r($test); // receive value }
i hope can give me input or examples.
may this:
function convertname($html, $elements) { $doc = new domdocument(); libxml_use_internal_errors(true); $doc->loadhtml($html); // loads html $xpath = new domxpath($doc); $elements = explode(';', $elements); $elemvalues = array(); foreach ($elements $element) { $nodelist = $xpath->query("//$element"); for($i=0; $i < $nodelist->length; $i++) $elemvalues[$element][] = $nodelist->item($i)->nodevalue; } return $elemvalues; } // testing $html = <<< eof <span class="bar">some normal text</span> <input type="hidden" name="hf" value="123"> <h1>heading 1<span> span inside h1</span></h1> <div class='foo'>some div</div> <span class="bold">bold text</span> <p/> eof; $elements = 'h1;span;'; // replace last ; / valid xpath $elements = preg_replace('#;(?=[^;]*;)#', '/', $elements); // call our function $elemvalues = convertname($html, $elements); print_r($elemvalues);
output:
array ( [h1/span] => array ( [0] => span inside h1 ) )
Comments
Post a Comment