Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php and Xpath - how to get text from inside a node

Tags:

php

xpath

How how can I get a text from inside a node using xpath?

For now I'm doing it like this:

$temp= $content->xpath('qwe/qwe');
$temp = each($temp[0]);
return $temp['value'];

But as you can see it's far from good solution :(

In c# it is as easy as

public string readXmlVar(string xpath)
{
    XmlNode xmlNode = xml.SelectSingleNode(xpath);
    return xmlNode.InnerText;
}
like image 764
NewProger Avatar asked Jun 27 '11 15:06

NewProger


4 Answers

For SimleXmlElement just cast it as a string: return (string) $temp;. For DomDocument use return $temp->nodeValue.

like image 150
prodigitalson Avatar answered Sep 21 '22 04:09

prodigitalson


Try:

$dom = new DOMDocument;
$dom->loadXML('<root>
    <p>some text<br />some more text</p>
</root>');

$xpath = new DOMXPath($dom);
foreach ($xpath->query('/root/p/text()') as $textNode) {
    echo $textNode->nodeValue;
}

$textNode will be a DOMText.

like image 27
Yoshi Avatar answered Sep 23 '22 04:09

Yoshi


(string) current($xml->xpath("//group[@ref='HS_TYP']"))

Hope that helps

like image 45
HKandulla Avatar answered Sep 20 '22 04:09

HKandulla


This will get all inner text from simple xml element

dom_import_simplexml($xpath->query('//div[@class="h1"]')->textContent;
like image 21
Selvamani Avatar answered Sep 19 '22 04:09

Selvamani