Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Edit XML with PHP Re: Edit XML with PHP

#78150
Capt Otis
Member

Makes much more sense. I actually did something like this not too long ago. So here’s how I did it…

I took the current xml file, and looped through it. I had my variables set for the old title, and the newly updated title so I knew which one to replace. I looped through the xml file and copied everything into a new xml, until I got to the outdated block. I then replaced it with the new information I wanted and continued my loop until the end. Once finished, I saved it overwriting the old xml file. And that’s it!

I modified my large piece of code to give you a smaller one that you should be able to use with little or no modifications. Let me know if you have any questions.

Code:
formatOutput = true;//why not?

$library = $doc->appendChild($doc->createElement(“pricing”));//creates

foreach($xml->package as $package) {//loops through the xml file

$b = $doc->createElement( “package” );//creates

if ($package->title == $oldtitle && $package->price == $oldprice && $package->description == $olddesc){//if we are at the outdated package, update information
$name = $doc->createElement( “title” );//creates element <br /> $name->appendChild($doc->createTextNode( $newtitle ));//adds $newtitle value inside the <br /> $b->appendChild( $name );//closes element
$price = $doc->createElement( “price” );
$price->appendChild($doc->createTextNode( $newprice ));
$b->appendChild( $price );
$desc = $doc->createElement( “description” );
$desc->appendChild($doc->createTextNode( $newdesc ));
$b->appendChild( $desc );
} else {//not at the package we want to update so simply copy over to our new xml
$name = $doc->createElement( “title” );
$name->appendChild($doc->createTextNode( $package->title ));
$b->appendChild( $name );
$price = $doc->createElement( “price” );
$price->appendChild($doc->createTextNode( $package->price ));
$b->appendChild( $price );
$desc = $doc->createElement( “description” );
$desc->appendChild($doc->createTextNode( $package->description ));
$b->appendChild( $desc );
}

$library->appendChild( $b );// }

$doc->save($xmlFile);//save our new xml in place of the old one. overwrites automatically.

}
updateXML(‘Package 1′,’$750′,’This is a description for Package 1.’,’a’,’a’,’a’);//will change package 1 to a for everything. example only

?>

-T