Appending an XML File Using PHP - php

I have a PHP file which contains a HTML form. When the user enters data into the form, it carries out error checking and if everything is in order the data entered is written to an XML file in a specific order. This part works perfectly. My problem is when the user fills in this form again, I need the new data to append to the XML file (not overwrite it). Currently, it simply over writes the data, could someone help me out on how I would do this? I tried watching tutorials but I am very new to XML and found them confusing. My XML file is as follows;
<?php
function createFile($xml_file)
{
$FileMessageID = $_POST['messageid'];
$FileCreation = $_POST['filedatetime'];
$FileTransactions = $_POST['filetransactions'];
$FileControlSum = $_POST['filecontrolsum'];
$CID = $_POST['CID'];
// create new dom document
$xml = new DOMDocument();
// these lines would create a nicely indented XML file
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;
// create a root element, and add it to DOM
addRoot($xml);
// add more elements to xml file
$CustomerDDInfo = $xml->createElement("CstmrDrctDbtInitn");
// add this element to the root
$xml->documentElement->appendChild($CustomerDDInfo);
// create elements
$GroupHeader = $xml->createElement("GrpHdr");
$InitiatingParty = $xml->createElement("InitgPty");
$IdentificationHeading = $xml->createElement("Id");
$PrivateIdentification = $xml->createElement("PrvtId");
$Other = $xml->createElement("Othr");
// append these elements to friend
$CustomerDDInfo->appendChild($GroupHeader);
$GroupHeader->appendChild($xml->createElement('MsgID', $_POST['messageid']));
$GroupHeader->appendChild($xml->createElement('CreDtTm', $_POST['filedatetime']));
$GroupHeader->appendChild($xml->createElement('NbOfTxs', $_POST['filetransactions']));
$GroupHeader->appendChild($xml->createElement('CtrlSum', $_POST['filecontrolsum']));
$GroupHeader->appendChild($InitiatingParty);
$InitiatingParty->appendChild($IdentificationHeading);
$IdentificationHeading->appendChild($PrivateIdentification);
$PrivateIdentification->appendChild($Other);
$Other->appendChild($xml->createElement('Id', $_POST['CID']));
$CustomerDDInfo->appendChild($PaymentInformation);
// save dom document to an xml file
$xml->save($xml_file);
}
function addRoot(&$xml)
{
$xml->appendChild($xml->createElement("entry"));
}
// call xml function
createFile('SEPA.xml');
//Redirect to Thank You Page
header ('Location: thankyou.php');
?>

load the existing XML document (if there is one)
add a child at the correct level with the information you would like to append
An XML is not like a text file, where you just put other data at the bottom of it. In XML you have to put the extra information inside a node somewhere inside the existing XML.
<exampleXML>
<item>
<name></name>
<number></number>
<date></date>
</item>
</exampleXML>
When another item to the XML you should load the XML, take the 'exampleXML' node and append a child to it.
Result:
<exampleXML>
<item>
<name></name>
<number></number>
<date></date>
</item>
<item>
<name></name>
<number></number>
<date></date>
</item>
</exampleXML>
I don't often work with XML DOM in PHP so I can't really provide you any code.
Look at http://www.php.net/manual/en/class.domdocument.php for the correct functions.

Related

XML File using PHP - Altering the First Two Lines UTF-8

I have an XML file which is formatted in a specific way with specific nodes. I have the following PHP code (in test.php) to create a new XML file each week or else append the XML file if an entry is within the same week;
$filename = date('Y-W').'.xml'; //2014-26.xml
//Check if a file exists
if (file_exists($filename))
{
// call xml appendFile function
appendFile($filename);
}
else
{
// call xml createFile function
createFile($filename);
}
When a new file is created (e.g. 2014-26.xml), the top two lines of the XML file are as follows;
<?xml version="1.0"?>
<entry>
I need the top two lines to be;
<?xml version=”1.0” encoding=”UTF-8”?>
<Document xmlns=”urn:iso:std:iso:20022:tech:xsd:pain.008.001.02” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”>
In my test.php file, I have the following function which is causing the "entry" node to be displayed;
function addRoot(&$xml)
{
$xml->appendChild($xml->createElement("entry"));
}
I call this function within the createFile function as follows;
// create a root element, and add it to DOM
addRoot($xml);
I tried simply changing "entry" to the second line which I require but I received an error. Anybody have any ideas as to how I would change these top two lines to suit my requirements as I have been attempting for days to no avail? I am very new to XML. Thanks.
Solution to Part 1;
I fixed the first line by entering adding "UTF-8" to this line of code as follows;
// create new dom document
$xml = new DOMDocument('1.0', 'UTF-8');
Solution to Part 2;
On the off chance that anyone else may have this problem, I was able to put the second line in by altering this code to;
function addRoot(&$xml)
{
$root = $xml->createElementNS('urn:iso:std:iso:20022:tech:xsd:pain.008.001.02', 'Document');
$xml->appendChild($root);
$root->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
}

How to delete a node in XML

Why is my code not functioning to delete an element located in my asset.xml
Here is my xml code inside a php file:
<?php
if(isset($_POST["delete"])) {
$node = $_GET["node"]; //get from form
$xmldoc->load('asset.xml');
$y= $xmldoc->getElementsByTagName("asset")[$node];
$xmldoc.documentElement.removeChild($y);}
?>
my xml file
<?xml version="1.0" encoding="UTF-8"?>
<Assets>
<asset>
<AssetType>PROJECTOR</AssetType>
<Product>DELL</Product>
<Brand>DELL</Brand>
</asset>
</Assets>
you need to first save file try
$xmldoc->save('asset.xml');
and
The removeChild() method removes a specified node.
The removeAttribute() method removes a specified attribute.
You'll have to save the file for the changes to persist
$xmldoc->save('asset.xml');
Seeing as the code you posted is actual code
DOMDocument::getElementsByTagName returns a DOMNodeList you'll have to access the elements via DOMNodelist::item
$y = $xmldoc->getElementsByTagName("asset")->item($node);//assuming $node is an integer < # of matched nodes
-> is used to access object properties in php not . so $xmldoc.documentElement.removeChild($y); should be
$xmldoc->documentElement->removeChild($y);
or better yet
$y->parentNode->removeChild($y);

How do I include an external XML file in PHP?

I need a way to include an external XML file in PHP which does not use simplexml tags. Furthermore, I'd also need it to integrate with other imported XMLs, hence removing file headers as <?XML version...>
Basically have a PHP class which includes methods to dynamically create XML elements based on user-input. For example, I could create a node called "test", set "id=1" as attribute and add child nodes to it. What I basically need, is a way to extract further XML content from other files and have my PHP script recognize it, hence being able to call methods on this imported code. I tried using php's fopen() function but, although it would print the imported XML to the screen, it would not validate and signal an error as soon as the imported code began. I cannot use simpleXML extension for two main reasons. Firstly, the entire class is written using Pre-PHP5 XML handling, and I cannot re-write the whole thing from scratch as it is part of a team-project, secondly, such class features methods which could not be replicated with simpleXML extension.
This is the XML I generate: <?xml version="1.0"?> <ga><dsa>hea</dsa><sda>eh</sda></ga> <gg><ds>he</ds><sd>eh</sd></gg> And it returns: Illegal Content, Line 3 Column 1, highliting the "<" of the "gg" tag... (Which, by the way, is the part imported from the external file.)
This is a snippet of the code used to print imported XML:
$file = simplexml_load_file($url);
foreach($file as $key => $value) {
echo "<" . $key . ">" . $value . "</" . $key . ">\n";
}
How can this be done?
Additional note: Yes, the server suppors PHP 5 (5.2.6), but the code was written in pre-php5.
Judging from your comments I'd say you get an error because a valid XML document needs a root element. You XML has two: <ga> and <gg>, which means the XML is invalid and cannot be parsed.
You should fix your XML by adding a root element. Then the parsing errors will go away.
Another option would be to load the snippet as a document fragment with DOM:
$brokenXML = <<< XML
<?xml version="1.0"?>
<ga><dsa>hea</dsa><sda>eh</sda></ga>
<gg><ds>he</ds><sd>eh</sd></gg>
XML;
$dom = new DOMDocument;
$fragment = $dom->createDocumentFragment();
$fragment->appendXML(trim(str_replace('<?xml version="1.0"?>', '', $brokenXML)));
echo $dom->saveXml($fragment);
Output:
<ga><dsa>hea</dsa><sda>eh</sda></ga>
<gg><ds>he</ds><sd>eh</sd></gg>
But note that this is still not a complete XML document because it misses a root element.
If you want to import a DOM Tree into another, you can use DOMDocument::importNode. To use that with the fragment above, you would do
$dom2 = new DOMDocument('1.0', 'utf-8');
$dom2->appendChild($dom2->createElement('foo'))
->appendChild($dom2->importNode($fragment, true));
echo $dom2->saveXml();
That would result in
<?xml version="1.0" encoding="utf-8"?>
<foo><ga><dsa>hea</dsa><sda>eh</sda></ga>
<gg><ds>he</ds><sd>eh</sd></gg></foo>
If you have an existing document you want to import to, you would simply do
$dom2 = new DOMDocument;
$dom2->load('existingFile.xml');
$dom2->documentElement->appendChild($dom2->importNode($fragment, true));
This would append the fragment as the last child of the root node. If you want to have it somewhere else on the DOM tree, you would have to traverse the DOM tree with Xpath or getElementsByTagName or getElementsById or the childNodes property on the various nodes and then append to that node instead.

Formatting output to file with PHP DOMDocument

So I wrote this script that looks for certain nodes in an XML file, deletes it, and puts a new node in it's place... however, the new node is showing up like so:
<PrintQuestion id="17767" type="pickOne">
<Standards><Standard value="CA.MATH-6-6-20" state="CA" grade="3" subject="MATH"/></Standards><References>
<PassageRef id="1892"/>
</References>
I've attempted to use the $xml->formatOutput = true; but that has done nothing. I'm loading the dom object from an XML file and saving it back to the same file upon completion.
When you want to use
$xml->formatOutput = TRUE;
you also have to set
$xml->preserveWhiteSpace = FALSE;
You wrote preserveWhitespace (mind the 2nd s). Properties are case-sensitive in PHP.
See difference on codepad

Moving a node from one XML document to another using SimpleXML

I realize that my request is not possible using just SimpleXML -- that much I did figure out. Here is what I tried:
$newXML = simplexml_load_file($filePath);
$domNewXML = dom_import_simplexml($newXML);
$domItem = dom_import_simplexml($items[$itemQty]); <-- item I want to move
$domNewItem = $domItem->cloneNode(true);
$newNode = $domNewXML->importNode($domNewItem, true);
$domNewXML->getElementsByTagName('list')->item(0)->appendChild($newNode);
I realize the code errors out on line 5, because importNode is a function of the dom document, not the dom element, but how can I get the dom document to perform this step?
Am I going about this the right way?
In the grand scheme of things I have an XML file with at least 10 nodes, every day a CRON job checks to see if there are more than 10 nodes and if so, it's supposed to move the node from the current file into an archive file. I figured I would "move" the node by copying it to the archive file and deleting it from the original file.
Thanks for any help!
You can get the owner document via $anyDOMNode->ownerDocument
Maybe it's not necessary to clone and insert the nodes into another document. If you split the archive into a) a skeleton xml document and b) an xml fragment that is included as an external entity into the document it suffices if you just append the xml string representation of the node to the end of the fragment file. E.g. as the skeleton
<?xml version="1.0"?>
<!DOCTYPE fooarchive [
<!ENTITY entries SYSTEM "archive.fragment">
]>
<fooarchive>
&entries;
</fooarchive>
and then the php script
$doc = new SimpleXMLElement('<a>
<b>0</b><b>1</b><b>2</b><b>3</b>
<b>4</b><b>5</b><b>6</b><b>7</b>
<b>8</b><b>9</b><b>X</b><b>Y</b>
</a>');
$move = '';
for($i=10; $i<count($doc->b); $i++) {
$move .= $doc->b[$i]->asXML();
}
file_put_contents('archive.fragment', $move, FILE_APPEND);
for($i=count($doc->b)-1; $i>9; $i--) {
unset($doc->b[$i]);
}
echo $doc->asXML('current.xml');

Categories