Replace specific node value in xml using php

Viewed 9936

Hi i am parsing multiple xml feed and combine into one and its working fine for me but now i am bit of stuck at one point because i need to add some prefix into specific node value i mean i need to change the value of that node. here i am providing some example code what actual i want.

XML

<JobRecords>
    <JobRecord>
        <Brand>Corporate1</Brand>
        <JobId>45982</JobId>
        <WorkTypes>
            <WorkTypeRecord>
                <Title>Permanent1</Title>
            </WorkTypeRecord>
        </WorkTypes>
    </JobRecord>
    <JobRecord>
        <Brand>Corporate2</Brand>
        <JobId>45983</JobId>
        <WorkTypes>
            <WorkTypeRecord>
                <Title>Permanent2</Title>
            </WorkTypeRecord>
        </WorkTypes>
    </JobRecord>
    <JobRecord>
        <Brand>Corporate3</Brand>
        <JobId>45984</JobId>
        <WorkTypes>
            <WorkTypeRecord>
                <Title>Permanent3</Title>
            </WorkTypeRecord>
        </WorkTypes>
    </JobRecord>
</JobRecords>    

In the above xml i want to append the prefix like this <JobId>0-45984</JobId>

Here is the php code which combine different xml feed into one give out put as above.

<?php 
    $feed1 = "data1.xml";
    $feed2 = "data2.xml"; 
    $feed3 = "data3.xml";

    $xml1 = new DOMDocument('1.0', 'UTF-8');
    $xml1->load($feed1);

    $xml2 = new DOMDocument('1.0', 'UTF-8');
    $xml2->load($feed2);

    $xml3 = new DOMDocument('1.0', 'UTF-8');
    $xml3->load($feed3);

    $addXml = array();
    $addXml[] = $xml1->saveXML();
    $addXml[] = $xml2->saveXML();
    $addXml[] = $xml3->saveXML();

    // create a new document
    $dom = new DOMDocument();
    $dom->appendChild($dom->createElement('JobRecords'));

    foreach ($addXml as $xml) {
      $addDom = new DOMDocument();
      $addDom->loadXml($xml);
      if ($addDom->documentElement) {
        foreach ($addDom->documentElement->childNodes as $node) {
          $dom->documentElement->appendChild(
            $dom->importNode($node, TRUE)
          );
        }
      }
    }

    $xmlFinal = $dom->saveXml();
    echo $xmlFinal;
?>  

I have tried so far but didn't succeed Please advise me how to achieve this.
Thanks in advance and much appreciated.

2 Answers
Related