0

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?

0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for this - is this just an alternative to the native DOM method?
@RichardOwens They're both as "native" as each other - they've both been part of PHP core since version 5. DOMDocument is more suited for parsing HTML that might not be well-formed, but (in my opinion at least), if your markup is valid then SimpleXML is a much nicer interface.
I agree with the simpler approach! Thank you.
Hmm - again, this doesn't seem to work. I'm not getting an error but the changes aren't being saved... I'll check the error log.
Sorry - not your error - mine! I had the wrong file_put_contents() path which led to permission problems. All works fine now. Thank you!
0

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.

1 Comment

As above - thank you - I'm trying to establish why this is the most appropriate when compared to the simplexml method provided :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.