How do I include an external XML file in PHP? - 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.

Related

Appending an XML File Using 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.

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);

Can I get an XML files structure without looking up the element names myself?

Using PHP, I would like to be able to open an XML file and get its structure without having to know any about the structure already. Is this possible?
I've been using XMLReader up until now but I'm parsing a wide variety of structures so it takes a while to go through each file manually and identify the structure.
I would only need to open the first parent node as every node after that would be the same.
e.g.
<name>
<first></first>
<second></second>
</name>
I would like to be able to identify this structure without having to manually look at the file first.
Happy to use other libraries than XMLReader but would need to stick with PHP.
Thanks!
DOMDocument should be able to do it.
$dom = new DOMDocument();
$dom->loadHTML($xml_data);
/* #var $names DOMNodeList */
$names = $dom->getElementsByTagName('name');
for($i=0;$i<$names->length;$i++){
$node = $names->item($i);
if($node->nodeName=='first'){
$first_name = $node->nodeValue; // store this
}elseif($node->nodeName=='second'){
$second_name = $node->nodeValue; // store this
}
}
Make sure that they are valid XML files.

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');

PHP SimpleXML new line

I have created a XML file using PHP's simple XML, saved the file. When opening the file in php using fopen and printing the contents. my XML looks like this: (see below)
<?xml version="1.0" encoding="UTF-8"?>
<home><orderList><delivery_cost>0.00</delivery_cost><delivery_surname>TEST</delivery_surname><delivery_postcode>1234</delivery_postcode><status>1</status></orderList></home>
I want the xml file looking all indented and on new lines for each element. Does anybody know how to do this?
Thanks
You can do this using the formatOutput property of DOMDocument.
Save your XML like this instead, presuming your XML is in a variable called $yourXML, and you want to save it to a file at $xmlFilePath:
$dom = new DOMDocument();
$dom->loadXML($yourXML);
$dom->formatOutput = true;
$formattedXML = $dom->saveXML();
$fp = fopen($xmlFilePath,'w+');
fwrite($fp, $formattedXML);
fclose($fp);
Code adapted from here.
This is called "pretty printing" and SimpleXML does not do that. If you search on Stack Overflow and elsewhere on the web you'll find custom solutions that do that.
Pretty printing is good for visulation but I don't recommend saving documents in that format.
If you're still looking for a pretty-printer, you can try SimpleDOM's asPrettyXML()
include 'SimpleDOM.php';
$home = simpledom_load_string('<?xml version="1.0" encoding="UTF-8"?>
<home><orderList><delivery_cost>0.00</delivery_cost><delivery_surname>TEST</delivery_surname><delivery_postcode>1234</delivery_postcode><status>1</status></orderList></home>');
echo $home->asPrettyXML();
echo "\n"; for new line in xml
ob_start(); echo '
' . "\n";?>

Categories