Page 1 of 1

simple code check please? PHP code to append xml file

Posted: Mon Sep 27, 2004 5:28 pm
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!

Posted: Mon Sep 27, 2004 5:31 pm
by feyd
You don't have matching delimiters for a regular expression.. look at the differences between your first and second preg.

Posted: Mon Sep 27, 2004 5:53 pm
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?

Posted: Mon Sep 27, 2004 5:59 pm
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...