9

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;
}
4
  • 1
    Just cast it as a string: return (string) $temp; Commented Jun 27, 2011 at 15:13
  • hm, that works :) Why didn't you wrote proper reply? I'd plus'ed you and selected your answer :) Commented Jun 27, 2011 at 15:16
  • php can be such a crazy language sometimes... you can never know what to do in some cases... Commented Jun 27, 2011 at 15:16
  • possible duplicate of obtain the node value as text with php + xpath Commented Jun 27, 2011 at 15:18

4 Answers 4

13

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

Sign up to request clarification or add additional context in comments.

1 Comment

One has to be careful thoguh, using $temp->nodeValue for DomDocument will return the text content from all children below the given node (including children of children).
10

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.

5 Comments

@Lurler Why? If you want all text content, just collect the node values. This is simple dom traversing, it's not even php specific.
Because it creates copy of the variable and then iterates over it. It's completely ineffecient.
Are you sure that is the case when you are dealing with objects? By nature isnt it a reference?
@prodigitalson To be honets, the way Lurler is responding on this topic, I don't thinks it makes much sense to discuss this any further.
@Yoshi: yes, premature micro-optimizers are an interesting breed ;-)
2
(string) current($xml->xpath("//group[@ref='HS_TYP']"))

Hope that helps

1 Comment

Much better. A simple and complete one-line solution to a simple question.
2

This will get all inner text from simple xml element

dom_import_simplexml($xpath->query('//div[@class="h1"]')->textContent;

1 Comment

OMG thank you - search a long while for this small command 👍

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.