How to fetch html string of XPath results?
Considering this code:
<div class="a">foo</div&g开发者_如何学运维t;
<div class="a"><div id="1">bar</div></div>
If I want to fetch all the values of divs with class a, I'll do the following query:
$q = $xpath->query('//div[@class="a"]');
However, I'll get this result:
foo
bar
But I want to get the actual value including the children tags. So it'll look like that:
foo
<div id="1">bar</div>
How can I accomplish that with XPath and DOMDocument only?
Solved by the function provided here.
PHP DOM has an undocumented '.nodeValue' attribute which acts exactly like .innerHTML
in a browser. Once you've used XPath to get the node you want, just do $node->nodeValue
to get the innerhtml.
You can try to use
$xml = '<?xml version=\'1.0\' encoding=\'UTF-8\' ?>
<root>
<div class="a">foo</div>
<div class="a"><div id="1">bar</div></div>
</root>';
$xml = simplexml_load_string($xml);
var_dump($xml->xpath('//div[@class="a"]'));
But in this case you will have to iterate objects.
Output:
array(2) { [0]=> object(SimpleXMLElement)#2 (2) { ["@attributes"]=> array(1) { ["class"]=> string(1) "a" } [0]=> string(3) "foo" } [1]=> object(SimpleXMLElement)#3 (2) { ["@attributes"]=> array(1) { ["class"]=> string(1) "a" } ["div"]=> string(3) "bar" } }
Try something like:
$doc = new DOMDocument;
$doc->loadHTML('<div>Your HTML here.</div>');
$xpath = new DOMXpath($doc);
$node = $xpath->query('//div[@class="a"]')->item(0);
$html = $node->ownerDocument->saveHTML($node); // Get HTML of DOMElement.
精彩评论