Combine XML Files using PHP

Viewed 291

Trying to combine the two xml files using php and then save a new merged xml.

http://alert.fcd.maricopa.gov/alert/Google/xml/fcdmc_alert_rain_v3.xml and http://alert.fcd.maricopa.gov/alert/Google/xml/fcdmc_alert_return.xml

<FCDMC>
<rpt_info created="07-06-2017 11:24"/>
<gage_rain id="770" last_rpt="2017-07-06T06:00:00" min_10="0.00" min_30="0.00" hour_1="0.00" hour_3="0.00" hour_6="0.00" day_1="0.00" day_3="0.00" day_7="0.00" cytd="1.77" rainscore="1" name="Tat Momolikot Dam [TM]" lat=" 32.65120" long="-111.92830"/>

and

<FCDMC>
<rpt_info created="07-06-2017 11:23"/>
<return_rain id="770" min10="0" min30="0" hour1="0" hour3="0" hour6="0" day1="0" day3="0" day7="0"/>

Want the output to look like this

<FCDMC>
<rpt_info created="07-06-2017 11:24"/>
<gage_rain id="770" last_rpt="2017-07-06T06:00:00" min_10="0.00" min_30="0.00" hour_1="0.00" hour_3="0.00" hour_6="0.00" day_1="0.00" day_3="0.00" day_7="0.00" cytd="1.77" rainscore="1" min10="0" min30="0" hour1="0" hour3="0" hour6="0" day1="0" day3="0" day7="0" name="Tat Momolikot Dam [TM]" lat=" 32.65120" long="-111.92830"/>

I am trying to write the PHP script but it has been unsuccesful. I am not getting any results or errors. XML is blank http://alert.fcd.maricopa.gov/alert/Google/xml/merged.xml as is the php http://alert.fcd.maricopa.gov/alert/Google/v3/php/merge_test.php.Here is the sript.

$doc1 = new DOMDocument();
$doc1->load('http://alert.fcd.maricopa.gov/alert/Google/xml/fcdmc_alert_rain_v3.xml');

$doc2 = new DOMDocument();
$doc2->load('http://alert.fcd.maricopa.gov/alert/Google/xml/fcdmc_alert_return.xml');

// get 'res' element of document 1
$res1 = $doc1->getElementsByTagName('gage_rain')->item(0); //edited res - items

// iterate over 'item' elements of document 2
$items2 = $doc2->getElementsByTagName('return_rain');
for ($i = 0; $i < $items2->length; $i ++) {
    $item2 = $items2->item($i);

    // import/copy item from document 2 to document 1
    $item1 = $doc1->importNode($item2, true);

    // append imported item to document 1 'res' element
    $res1->appendChild($item1);

}
$doc1->save('http://alert.fcd.maricopa.gov/alert/Google/xml/merged.xml'); //edited -added saving into xml file

Anyone know what is wrong here?? I would like the php to save the desired output as a new merged xml file at location http://alert.fcd.maricopa.gov/alert/Google/xml/merged.xml.

1 Answers
Related