1

I have this XML:

<root> <parent> <child id="childAtt"> <subChild id="subAtt">Value to retrieve</subChild> </child> </parent> </root> 

I am currently trying to retrieve the text value of subChild using this XPath:

$total = $xml->xpath("/*//child[@id='childAtt']/subChild[@id='subAtt']"); 

However, this returns the subChild attribute value and not the node's text value.

I want to know how to retrieve the text value of subChild with the id of subAtt.

3 Answers 3

1

You just need to access the first element and typecast it as a string:

$total = (string) $xml->xpath("/*//child[@id='childAtt']/subChild")[0]; var_dump($total); 

Output:

string(17) "Value to retrieve" 
Sign up to request clarification or add additional context in comments.

Comments

0

You can also try to extract the text directly with your XPath query:

$total = (string) $xml->xpath("/*//child[@id='childAtt']/subChild/text()") 

Comments

0

Your query does select the element. Just to expand @Amal's answer, the result of your query is an array of all results that looks like this:

array(1) { [0] => class SimpleXMLElement#2 (2) { public $@attributes => array(1) { 'id' => string(6) "subAtt" } string(17) "Value to retrieve" } } 

In words: the first element is a SimpleXMLElement instance whose string value is the desired text.

A complete example:

$string = <<<XML <root> <parent> <child id="childAtt"> <subChild id="subAtt">Value to retrieve</subChild> </child> </parent> </root> XML; $xml = new SimpleXMLElement($string); $result = $xml->xpath("/*//child[@id='childAtt']/subChild[@id='subAtt']"); var_dump($result); print (string) $result[0] . "\n"; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.