simple code check please? PHP code to append xml file

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
Calipoop
Forum Newbie
Posts: 24
Joined: Fri Sep 17, 2004 6:06 pm
Location: Los Angeles, CA

simple code check please? PHP code to append xml file

Post by Calipoop »

I want to append an xml node to an existing xml file. I'm sending xml data from flash to a php file with the following code:

Code: Select all

<?php
//variables
$raw_xml = file_get_contents('php://input');
$stories = file_get_contents("Stories.xml");

//ignore the document type
$raw_xml = preg_replace("/\<\?xml.*?\>/", '', $raw_xml);
$raw_xml = trim($raw_xml);

//add new story
$stories = preg_replace("</stories>", "$raw_xml </stories>", $stories);

//open the file for writing
$fp = fopen("Stories.xml", "wb");

//write to file
fwrite($fp, $stories);
fclose($fp);

//send to flash
print $stories;
?>
To keep it easy, I'm simply replacing the xml closing tag with the new node+closing tag (line 11). But my php code doesn't seem to work!

Seems like an php-xml append script should be fairly easy/common, but I haven't found anything online except for the simple script on Kirupa.com, which won't work if two instances of the xml file are open at the same time. (one of the stories gets deleted in that case).

Thanks for your help!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

You don't have matching delimiters for a regular expression.. look at the differences between your first and second preg.
Calipoop
Forum Newbie
Posts: 24
Joined: Fri Sep 17, 2004 6:06 pm
Location: Los Angeles, CA

Post by Calipoop »

yeah, line 8 and 9 I copied from another user's file, but I don't completely understand when or why to use delimiters. Would anyone be able to explain or point me to a good tutorial for that?

I assume it's to sort through the characters that are added to the string during conversion. Would all I need to do is match the "/\<\" and the "\>/" at the beginning and end?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

when you are using the preg functions, you have to, 100% of the time, use pattern delimiters. This is because the preg functions have modifiers that can be appended to the pattern string. the / or any other symbol like #, $, %, ^, @, &, *, (, ), -, _, =, +, `, ~, etc.. can be used.. however, unless you know what you're doing, I wouldn't use a symbol that's also a pattern metacharacter like |, (, ), ^, *, $, etc...
Post Reply