PHP SimpleXMLElement
can access XML and also give me the text content of an element with the implicit string cast conversion. But I see no way to change that text content. Is it possible?
I have this XML:
<root>
<element>text</element>
</root>
The text in the element can be accessed like this:
$xml = new SimpleXMLElement($xmlStr);
$element = $xml->xpath('/root/element');
echo $element;
But what I also need is setting the text so that the XML looks like that:
<root>
<element>new text</element>
</root>
$element = 'new text';
This obviously doesn’t work. But I don’t even know what to try. It’s not documented and I couldn’t find anything on the web. A class that makes me search so much for simple usage can’t be "simple".
The JavaScript equivalent would be:
element.textContent = "new text";
2
Answers
This should do the trick:
SimpleXML is limited.
PHP supports DOM and Xpath. Xpath is actually a little easier to use – compared to the browser.
DOMXpath::evaluate()
returns a list of nodes or a scalar value depending on the expression.