php - How can I get text only from the current node with DOMElement? -
<div> <a>abc</a> xyz </div>
given above html structure, $divelement->nodevalue
returns 'abc xyz', when want 'xyz' only. $divelement->getattribute('value')
empty.
how can 'xyz' without removing <a>
element?
just iterate through <div>
, combine text node:
$dom=new domdocument; $dom->loadhtml(<<<html <div> <a>abc</a> xyz </div> html ); $div=$dom->getelementsbytagname("div")->item(0); var_dump($div->childnodes->length);//just debug $txt=""; foreach(range(0,$div->childnodes->length-1) $idx) { if($div->childnodes->item($idx)->nodetype==3) { $txt.=$div->childnodes->item($idx)->nodevalue; } } var_dump($txt);
nodetype==3
means text node. corresponding nodename
#text
.
Comments
Post a Comment