boen_robot Posted November 12, 2006 Share Posted November 12, 2006 Eurika!"Add" function just implemented. The thing I was missing was the setAttribute() function. I'm still thingking on how to generate the new ID properly, and I'm up to creating a delete and edit functions, but this is still a great progress: <?php//Prepare the variables and constants$xmlFile = "photo.xml"; //Your XML file$action = $_POST["action"]; //What are we going to do with it$DBroot = "images"; //This is the element storing everything else.$DBunit = "image"; //The elements you have in the pseudo DB.//Prepare the XML file.$dom = new DomDocument;$dom->formatOutput = true;$dom->preserveWhiteSpace = true;$dom->load($xmlFile);$xpath = new DomXPath($dom);//Perform the desired actionswitch($action){ case "add": $parent_path = "/" . $DBroot; $next_path = "/" . $DBroot . "/" . $DBunit . "[position() = last() + 1]"; // Find parent node $parent = $xpath->query($parent_path); // new node will be inserted before this node $next = $xpath->query($next_path); // Create the new element $newDBunit = $dom->createElement($DBunit); //Create all of the element's attributes foreach ($_POST as $attribute => $value) { if (!empty($value) && $attribute !== "action") { $newDBunit->setAttribute($attribute,$value); } } //The new ID is the number of elements + 1. //Unfrortunatly, this doesn't cover the situation when some item is missing, but the ID must still increment. $newDBunit->setAttribute("id",$xpath->evaluate("count(//@id)") + 1); // Insert the new element and the whitespaces around it. $whiteSpaceBefore = $dom->createTextNode(" "); $whiteSpaceAfter = $dom->createTextNode("\n"); $parent->item(0)->insertBefore($whiteSpaceBefore, $next->item(0)); $parent->item(0)->insertBefore($newDBunit, $next->item(0)); $parent->item(0)->insertBefore($whiteSpaceAfter, $next->item(0)); $content = $dom->saveXML(); break; case "remove": die("REMOVE Not implemented"); break; case "edit": die("EDIT Not implemented"); break;}//Save the output and notify if there are any errors.$writingToFile = file_put_contents($xmlFile,$content);if (!$writingToFile) {die("Error writing to file");}echo "File written successfully. The new file is " . $writingToFile . " bytes large.";?> Link to comment Share on other sites More sharing options...
kvnmck18 Posted December 21, 2006 Author Share Posted December 21, 2006 Goooooood stuff. God, I've been so busy lately. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now