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');
}
Related
maybe someone can help me, i provide xml files witch are generated from a PHP DB query and each xml file has a unique name. Now i want to prepare a function like "get the latest xml file" but I don't know whats the best way!
$xml = simplexml_load_file('test.xml');
I found this function but there i have to know the exact name!
or ist something like this possible:
$xml = simplexml_load_file('test.php');
and in the test.php i have a function to get the last name, but how to i provide the xml data?
Some keywords how i can find a solution in google would be very helpful!
The first parameter to that function is a string of the filename. The file should be the XML file to load, so you cant use another php file.
http://php.net/manual/en/function.simplexml-load-file.php
So you need to get the filename as a string first by using a variable. You should be able to copy the code in your test.php file, then save the filename instead of echoing it out. Then you use that variable when loading the xml file.
e.g.
function get_latest_filename()
{
//contents of your test.php file should set this variable
$latest_filename = 'the_latest_file.xml';
return $latest_filename;
}
$latest = get_latest_filename();
$xml = simplexml_load_file($latest);
here the finish solution that worked for me
i protected the directory with .htaccess and inside i store all my generated xml files and also the getLastXml.php file!
the getLastXml.php
function get_last_file() {
$lastFileTime = 0;
foreach (glob("*.xml") as $filename) {
if ($lastFileTime<filemtime($filename))
{
$lastFileTime = filemtime($filename);
$lastFileName = $filename;
}
}
return $lastFileName;
}
$lastXmlFile = get_last_file();
header ("Content-Type:text/xml");
echo file_get_contents($lastXmlFile);
the functions get_last_file() returns the name of the latest created xml file and
header ("Content-Type:text/xml");
displays xml in the php file
echo file_get_contents($lastXmlFile);
loads the content of the xml file and display it
simplexml_load_file("http://username:passwort#urlToTheDirectory/getLastXml.php");
loads the xml data with
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.
I tried many ways to save xml file on my filesystem, but it doesn't work. I don't know what can I do...
I only want to read an xml file, then modify the value of a node, and then save this file... But nothing happened. In PHP I don't know what the problem. In Java okay... but I need to do in PHP.
XML file:
<?xml version="1.0"?>
<node>
<pass>test</pass>
</node>
public static function saveToXML()
{
$xml = simplexml_load_file(dirname(__FILE__).'/../../../../sms_data.xml');
$xml->pass = "000";
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
echo $dom->saveXML();
}
The $xml is contains the modified values. It is good, but the save function doesn't wanna work!
I tried this too: echo $dom->save('text.xml'); But nothing. It doesn't create the text.xml file... I don't know... I have been searching for the solutions on google for one day. But I don't know what the hell is going to always wrong. I didnt get nothing. The server log is empty about it...
I am so sorry to ask this. But I don't understand this code why doesn't work... why doesn't save the modification on filesystem level!
Check if the directory exists and is writable.
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.
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');