skip to Main Content

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


  1. This should do the trick:

       $xml = new SimpleXMLElement("<root><element>text</element></root>");
       $element = $xml->xpath('/root/element');
       $element[0][0] = "new text";
       echo $xml->asXML();
    
    Login or Signup to reply.
  2. 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.

    $xml = '<root><element>text</element></root>';
    
    $document = new DOMDocument();
    $document->loadXML($xml);
    $xpath = new DOMXpath();
    
    // fetch and iterate nodes
    foreach ($xpath->evaluate('(/root/element)[1]') as $element) {
        // modify node
        $element->textContent = "new text";
    }
    
    echo $document->saveXML();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search