in PHP by (16.3k points)
0 like 0 dislike

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 (16.3k 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();

Please log in or register to answer this question.