XML/PHP: XML doesnt get written properly by my script -
i seem have small problem, whenever insert information via form xml file, adds information directly in previous's entry's child, instead of creating new child, entry, this:
<people> <person> <name>lighty</name> <age>17</age> <sex>m</sex> <comment>iets</comment> <name>darky</name><age>22</age><sex>f</sex><comment>things</comment></person>
while need have something, this:
<people> <person> <name>lighty</name> <age>17</age> <sex>m</sex> <comment>iets</comment> </person> <person> <name>darky</name> <age>22</age> <sex>f</sex> <comment>iets</comment> </people>
i tried using "$xml->formatoutput = true;" line, add child formatoutput 1 filled in, complete fail.
any idea im doing wrong? here m php code:
<?php echo ('script started'); //making sure script runs when use post if ($_server["request_method"] == "post") { echo ('-post accepted'); //load xml file variable $xml = simplexml_load_file("phptest3.xml"); echo ('-xml loaded'); //connect form variables $name = $_post['name']; $age = $_post['age']; $sex = $_post['sex']; $comment = $_post['comment']; echo ('-vars connected'); //function strip items not needed prevend xss/injections function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } echo ('-injections stripped'); //create new children in xml file , connect data corresponding xml entries $xml->formatoutput = true; $xml->people[0]; $xml->people->addchild('person'); $xml->person->addchild('name', $name); $xml->person->addchild('age', $age); $xml->person->addchild('sex', $sex); $xml->person->addchild('comment', $comment); echo ('-data inserted'); //save current data xml file... $xml->savexml('phptest3.xml'); echo ('-saved'); } echo ('-script ended.'); ?>
you can combination of simplexmlelement , domdocument.
this how did it:
<pre> <?php // orignal xml - starting empty $xmlstr = "<?xml version='1.0' standalone='yes'?> <people></people>"; // load xml $people = new simplexmlelement($xmlstr); // debug (before add) echo "<b>before</b> add\r\n"; print_r($people); echo "<hr>\r\n\r\n"; // add first person $newperson = $people->addchild('person'); $newperson->addchild('name', 'lighty'); $newperson->addchild('age', 17); $newperson->addchild('sex', 'm'); $newperson->addchild('comment', 'iets'); // debug (after add) echo "<b>after</b> add\r\n"; print_r($people); echo "<hr>\r\n\r\n"; // output modified xml formatting $dom = new domdocument; $dom->preservewhitespace = false; $dom->loadxml($people->asxml()); $dom->formatoutput = true; echo $dom->savexml(); ?>
browser outout:
formatted xml output:
<?xml version="1.0" standalone="yes"?> <people> <person> <name>lighty</name> <age>17</age> <sex>m</sex> <comment>iets</comment> </person> </people>
hope helps.
Comments
Post a Comment