Jump to content
Sign in to follow this  
kvnmck18

Submitting from a PHP Form to XML document

Recommended Posts

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.";?>

Share this post


Link to post
Share on other sites

Goooooood stuff. God, I've been so busy lately.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...