Appending XML

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ajayashish
Forum Newbie
Posts: 1
Joined: Fri Nov 14, 2008 3:29 am

Appending XML

Post by ajayashish »

Silly question:

I have never worked with php and now am in a problem. working with flex i need to write a small php code which writes XML.

I am able to append the xml file with this quote

<?php
$test = "<row label='".$_REQUEST['firstname']." ".$_REQUEST['lastname']."'/>";
$open = fopen("contact.xml", 'a');
$write = fwrite($open, $test);
?>

But the problem is it appends the line at the end.

<?xml version='1.0' encoding='ISO-8859-1' ?>
<rows>
<row label='Ajay Jain'/>
</rows><row label='Ashish Jain'/>

I want to append the line before </rows> and in a different line. That means it should look like

<?xml version='1.0' encoding='ISO-8859-1' ?>
<rows>
<row label='Ajay Jain'/>
<row label='Ashish Jain'/>
</rows>

Can anyone help me in the codes...
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Appending XML

Post by requinix »

Easy solution:

Code: Select all

$xml = file_get_contents("contact.xml");
$xml = str_replace("</rows>", '<row label="'.htmlentities($_REQUEST['firstname'].' '.$_REQUEST['lastname'])."\"/>\n</rows>", $xml);
$h = fopen("contact.xml", "w"); flock($h, LOCK_EX);
fwrite($h, $xml);
fclose($h);
 
Better solution (but only if you have PHP 5 and SimpleXML):

Code: Select all

$xml = simplexml_load_file("contact.xml");
$xml->appendChild("row");
$xml->addAttribute("label", $_REQUEST['firstname']." ".$_REQUEST['lastname']);
$h = fopen("contact.xml", "w"); flock($h, LOCK_EX);
fwrite($h, $xml->asXML());
fclose($h);
Post Reply