in PHP by (14.9k points)
0 like 0 dislike
32 views

I want update value of a specific node in XML with help use SimpleXMLElement class and XPath query in PHP PL. I need to change text from nodes of SimpleXML with help XPath in PHP. How I can to do it?

Suitable search queries for this question
  • change simplexml node value by xpath in php
  • php simplexml xpath change node value
  • php change xml node by xpath

1 Answer

0 like 0 dislike
by (14.9k points)

Interpret a string of XML into an SimpleXMLElement object:

$xml = simplexml_load_string($xmlDataStr);

Assume XML data are in $xmlDataStr string variable.

Using XPath query:

$qryRsl = $xml->xpath('/some/xpath/query/here');

The query results are stored as SimpleXMLElement elements in an $qryRsl array.

Iterate over and change all selected nodes:

foreach ($qryRsl as $curRslItm) {
    $curRslItm[0] = 'New txt';
}

Or like this:

foreach ($qryRsl as $key => $val) {
    $qryRsl[$key][0] = 'New txt';
}

Or any specified item, if it has in query result array:

if (isset($qryRsl[3])) {
    $qryRsl[3][0] = 'New txt';
}

Take a look at the changed XML:

echo $xml->asXML();

Your answer

Try to answer the question as detailed as possible.
Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.