Richard Owens
Richard Owens

Reputation: 155

PHP Update Simple Xml File

I have searched around a bit and the answer seems to lie in using a DOM object but, after a lot of tinkering, I can't get any of the examples to work and I can't work out what I'm doing wrong. It may be that I'm just using the wrong method.

The xml is really simple..

<?xml version="1.0" encoding="utf-8"?>
<courseinfo>
    <info>Under inspection (decision 13:15)</info>
    <buggies>Yes</buggies>
    <trolleys>No</trolleys>
</courseinfo>

All I want to do is to update and save the child nodes <info>, <buggies> and <trolleys> using form strings.

What is the best way to approach this?

Upvotes: 0

Views: 402

Answers (2)

iainn
iainn

Reputation: 17434

If you need to modify an existing XML document, you can use the SimpleXML Extension to manipulate it using standard PHP object access.

$xml = file_get_contents('foo.xml');

$sxml = simplexml_load_string($xml);

$info = 'New info';
$buggies = 'New buggies';
$trolleys = 'New trolleys';

$sxml->info = $info;
$sxml->buggies = $buggies;
$sxml->trolleys = $trolleys;

file_put_contents('foo.xml', $sxml->asXML());

See https://eval.in/942615

Upvotes: 1

Marcel
Marcel

Reputation: 5119

The most appropriate way is using the PHP native DomDocument class.

$oDoc = new DomDocument('1.0', 'utf-8');

$oInfo = $oDoc->createElement('info', 'under inspection (decision 13:15)');
$oBuggies = $oDoc->createElement('buggies', 'Yes');
$oTrolleys = $oDoc->createElement('trolleys', 'No');

$oCourseinfo = $oDoc->createElement('courseinfo');
$oCourseinfo->appendChild($oInfo);
$oCourseinfo->appendChild($oBuggies);
$oCourseinfo->appendChild($oTrolleys);

$oDoc->appendChild($oCourseinfo);

echo $oDoc->saveXML();

Simple as pie.

Upvotes: 0

Related Questions