Replace specific node value in xml using php

一曲冷凌霜 提交于 2019-12-05 09:59:28

You could iterate from root and check and replace the node like following. Here $xmlData holds the string of your xml.

$dom = new DOMDocument();
$dom->loadXML($xmlData);
foreach ($dom->documentElement->childNodes as $node) {
//print_r($node);
if($node->nodeType==1){
   $OldJobId = $node->getElementsByTagName('JobId')->Item(0);
   $newelement = $dom->createElement('JobId','0-'.$OldJobId->nodeValue); 
    $OldJobId->parentNode->replaceChild($newelement, $OldJobId);
 }
}
$str = $dom->saveXML($dom->documentElement);
echo $str;

You can find working demo here

ThW

I am not sure why you don't load the xml feed directly inside the loop, like in the second example of the previous answer.

After importing the 'JobRecord' element into the target, document, you have to find it JobId child and modify it's nodeValue property

$files= array(
  'xml1.xml',
  'xml2.xml',
  'xml3.xml'
  // ... more xmls
);

$dom = new DOMDocument();
$dom->appendChild($dom->createElement('JobRecords'));
// get an xpath object
$xpath = new DOMXpath($dom);

// $index variable for later use
foreach ($files as $index => $filename) {
  $addDom = new DOMDocument();
  $addDom->load($filename);
  if ($addDom->documentElement) {
    foreach ($addDom->documentElement->childNodes as $node) {
      $dom->documentElement->appendChild(
        $record = $dom->importNode($node, TRUE)
      );
      // find the jobId child elements (should be only one)
      $jobIds = $xpath->evaluate('./JobId', $record);
      foreach ($jobIds as $jobId) {
        // prefix the value with the index
        $jobId->nodeValue = $index.'-'.$jobId->nodeValue;
      }
    }
  }
}

echo $dom->saveXml();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!