Generate XML using PHP - php

I have the following PHP code from which I need to generate XML.
$hparams["SiteName"]="";
$hparams["AccountCode"]="";
$hparams["UserName"]='xxxx';
$hparams["Password"]='xxxx';
$client_header = new SoapHeader('url','AuthenticationData',$hparams,false);
$cliente = new SoapClient($wsdl); $cliente->__setSoapHeaders(array($client_header));
$opta=array();
$opta["Search"]["request"]["Origin"]="MAA";
$opta["Search"]["request"]["Destination"]="BOM";
$opta["Search"]["request"]["DepartureDate"]="2014-05-20T00:00:00";
$opta["Search"]["request"]["ReturnDate"]="2014-05-22T00:00:00";
$opta["Search"]["request"]["Type"]="OneWay";
$opta["Search"]["request"]["CabinClass"]="All";
$opta["Search"]["request"]["PreferredCarrier"]="";
$opta["Search"]["request"]["AdultCount"]="1";
$opta["Search"]["request"]["ChildCount"]="0";
$opta["Search"]["request"]["InfantCount"]="0";
$opta["Search"]["request"]["SeniorCount"]="0";
$opta["Search"]["request"]["IsDirectFlight"]="true";
$opta["Search"]["request"]["PromotionalPlanType"]="Normal";
$h=array();
$h= (array)$cliente->__call('Search',$opta);
How can I generate an XML of the above variables in PHP ?
The format should be
<xml>
<credential>
<Sitename>sitename</Sitename>
<AccountCode>ACC Code</AccountCode>
</credentials>
<Data>
<Origin>MAA</Origin>
<Destination>BOM</Destination>
</Data>
</xml>
Any help would be appreciate.
Thank you.

<?php
ini_set('error_reporting', E_ALL);
$dom = new DomDocument('1.0'); // making xml
$credentials = $dom->appendChild($dom->createElement('Credentials')); // adding root element <credentials>
$sitename = $credentials->appendChild($dom->createElement('Sitename')); // adding element <sitename> in <credentials>
$accountcode = $credentials->appendChild($dom->createElement('AccountCode')); // adding element <accountcode> in <credentials>
$sitename->appendChild($dom->createTextNode('sitename')); // adding text in <sitename>
$accountcode->appendChild($dom->createTextNode('ACC Code')); // adding text in <accountcode>
$data = $dom->appendChild($dom->createElement('Data'));
$origin = $data->appendChild($dom->createElement('Origin'));
$destination = $data->appendChild($dom->createElement('Destination'));
$origin->appendChild($dom->createTextNode('MAA'));
$destination->appendChild($dom->createTextNode('BOM'));
$dom->formatOutput = true; // generating xml
// generating XML as string or file
$test1 = $dom->saveXML();
$dom->save('test1.xml');
?>
I think you could write loop by yourself ;)
P.S. PHP 5+

First of all, your xml is not well structured.
It should be like:
<xml>
<credentials>
<Sitename>sitename</Sitename>
<AccountCode>ACC Code</AccountCode>
<Data>
<Origin>MAA</Origin>
<Destination>BOM</Destination>
</Data>
</credentials>
<credentials>
...
</credentials>
</xml>
Iterate the obtained result, and by concating , form the needed xml.

Related

XML PHP Format Setup

Is there a why to do this? I'm new on create DomDocument. Thank you
<!DOCTYPE Data SYSTEM "http://data.data.org/schemas/data/1.234.1/data.dtd"> <Data payloadID = "123123123131231232323" timestamp = "2015-06-10T12:59:09-07:00">
$aribaXML = new DOMImplementation;
$dtd = $aribaXML->createDocumentType('cXML', '', 'http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd');
$dom = $aribaXML->createDocument('', '', $dtd);
Here are two ways in DOM to create a new document in PHP. If you don't need the DTD you can directly create an instance of the DOMDocument class.
$document = new DOMDocument('1.0', "UTF-8");
$document->appendChild(
$cXML = $document->createElement('cXML')
);
echo $document->saveXML();
Output:
<?xml version="1.0" encoding="UTF-8"?>
<cXML/>
For a document with a DTD your approach was correct.
$implementation = new DOMImplementation;
$dtd = $implementation->createDocumentType(
'cXML', '', 'http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd'
);
$document = $implementation->createDocument("", "cXML", $dtd);
$document->encoding = 'UTF-8';
$cXML = $document->documentElement;
echo $document->saveXML();
Output:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd">
After the initial bootstrap you use methods of the $document to create nodes and append them.
// set an attribute on the document element
$cXML->setAttribute('version', '1.1.007');
// xml:lang is a namespaced attribute in a reserved namespace
$cXML->setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:lang', 'en-US');
// nested elements
// create a node, store it for the next call and append it
$cXML->appendChild(
$header = $document->createElement('Header')
);
$header->appendChild(
$from = $document->createElement('From')
);
$from->appendChild(
$credential = $document->createElement('Credential')
);
// "Identity" has only a text node so we don't need to store it for later
$credential->appendChild(
$document->createElement('Identity')
)->textContent = '83528721';
// format serialized XML string
$document->formatOutput = TRUE;
echo $document->saveXML();
Output:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.014/cXML.dtd">
<cXML version="1.1.007" xml:lang="en-US">
<Header>
<From>
<Credential>
<Identity>83528721</Identity>
</Credential>
</From>
</Header>
</cXML>
$xml = new DomDocument('1.0');
$xml->formatOutput = true;
$works = $xml->createElement("works");
$xml->appendChild($works);
$work = $xml->createElement("work");
$work->setAttribute("id",1);
$works->appendChild($work);
$xml->save("storage/document.xml") or die("Error, Unable to create XML File");

How to load string back xml with simpleXML in PHP?

Would anyone know how i can "explode" a string back into "normal" xml format?
I found this script (ref:gooseflight,2010) that looks like it can do the job but the output comes out stuck together.
Here's the code:
enter code herefunction combineXML($file)
{
global $xmlstr;
$xml = simplexml_load_file($file);
foreach($xml as $element)
$xmlstr .= $element->asXML();
}
$files[] = "tmp.xml";
$files[] = "traduction.xml";
$xmlstr = '<CAB>';
foreach ($files as $file)
combineXML($file);
$xmlstr .= '</CAB>';
// Convert string to XML for further processing
$xml = simplexml_load_string($xmlstr);
$bytes = file_put_contents("combined.xml", $xml->asXML())
Here is the output:
<?xml version="1.0" encoding="UTF-8"?>
<CAB>
<CABO>XXXXXXXXXX0987650003</CABO><ACTIVITY>NONE</ACTIVITY><BEORI>blablaE</BEORI>BEDEST>blabla</BEDEST><NATRELA>more blabla</NATRELA><ANE>2014</ANE><NODEP>1111</NODEP>
</CAB>
So how could i seperate the nodes to look like this?:
<?xml version="1.0" encoding="UTF-8"?>
<CAB>
<CABO>XXXXXXXXXX0987650003</CABO>
<ACTIVITY>NONE</ACTIVITY>
<BEORI>blablaE</BEORI>
<BEDEST>blabla</BEDEST>
<NATRELA>more blabla</NATRELA>
<ANE>2014</ANE>
<NODEP>1111</NODEP>
.....
</CAB>
Would anyone know how to fix it?
I would suggest to use DomDocument class to save the XML; check this:
$dom_obj = new DOMDocument();
$dom_obj->loadXML($file);
// Do all your changes to the file by using DomDocument command (e.g. CreateElement, CreateAttribute, etc)
$dom_obj->formatOutput = true;
$dom_obj->save($file);

XML Encoding generated from PHP

I am doing an assignment for class where I have to use a Java Servlet running on Tomcat and have it message a php file to scrape IMDB for movie information and return it as XML to the servlet. It seems to not want to accept any encoding I give it as I continuously get XML tags such as the ones below.
<result cover="url" title="Pokémon" year="1998 TV Series" director="N/A" rating="7.8" details="http://www.imdb.com/title/tt0176385/"/>
Where title of Pokemon should have an accent over the e («é»). I have the following php code to generate the xml. (Important parts only)
<?php header("Content-Type: text/xml; charset=utf-8");
$xml = new DOMDocument();
$rsp = $xml->appendChild($xml->createElement("rsp"));
$xml->encoding = 'utf-8';
$titleNames[$i] = utf8_encode($title_tmp[1]);
$results = $rsp->appendChild($xml->createElement("results"));
$results->setAttribute("total", $tableRows);
$item->setAttribute("title", $titleNames[$i]);
echo $xml->saveXML();
?>
Any help would be greatly appreciated in figuring out how to correctly display special characters!
It's impossible to say what's wrong from your code fragments (which don't even run) but $xml->encoding = 'utf-8' should work. Please compare:
$xml = new DOMDocument();
$rsp = $xml->appendChild($xml->createElement("rsp"));
$rsp->setAttribute("title", 'Pokémon');
echo $xml->saveXML();
/*
<?xml version="1.0"?>
<rsp title="Pokémon"/>
*/
... with:
$xml = new DOMDocument();
$xml->encoding = 'utf-8';
$rsp = $xml->appendChild($xml->createElement("rsp"));
$rsp->setAttribute("title", 'Pokémon');
echo $xml->saveXML();
/*
<?xml version="1.0" encoding="utf-8"?>
<rsp title="Pokémon"/>
*/
(These snippets are expected to be saved as UTF-8).

XML creation on the fly using PHP

I have a small requirement where I need to create a XML file on the fly. It was no problem for me to create a normal xml file which would be looking like this:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<item>
<name></name>
</item>
</root>
But my requirement is such that I need to create a XML file whose output is:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<item>
<name url = "C:\htdocs\proj1\source_file1"/>
<name url = "C:\htdocs\proj1\source_file2"/>
<name url = "C:\htdocs\proj1\source_file3"/>
</item>
</root>
I have tried in this fashion:
<?php
$domtree = new DOMDocument('1.0', 'UTF-8');
$domtree->formatOutput = true;
$xmlRoot = $domtree->createElement("root");
$xmlRoot = $domtree->appendChild($xmlRoot);
$item = $domtree->createElement("item");
$item = $xmlRoot->appendChild($item);
$name= $domtree->createElement("name");
$name = $item->appendChild($name);
$sav_xml = $domtree->saveXML();
$handle = fopen("new.xml", "w");
fwrite($handle, $sav_xml);
fclose($handle);
?>
But I wanted to append/add the url="path" to my elements. I have tried declaring variables with url and path but this throws me errors like:
Uncaught exception 'DOMException' with message 'Invalid Character Error'
Any ideas how to approach this problem!
Thanks
You just have to declare that attributes via php DOM:
...
$name= $domtree->createElement("name");
$urlAttribute = $domtree->createAttribute('url');
$urlAttribute->value = 'C:\htdocs\proj1\source_file1';
$name->appendChild($urlAttribute);
$item->appendChild($name);
...
Link to DOMDocument docs

Adding node using PHP's SimpleXML to XML with namespaces

<?xml version="1.0" encoding="ISO-8859-2"?>
<!DOCTYPE pasaz:Envelope SYSTEM "loadOffers.dtd">
<pasaz:Envelope xmlns:pasaz="http://schemas.xmlsoap.org/soap/envelope/">
<pasaz:Body>
<loadOffers xmlns="urn:ExportB2B">
<offers />
</loadOffers>
</pasaz:Body>
</pasaz:Envelope>
I've to add some child nodes to "offers" node and I'm using SimpleXML.
The PHP code: $offer = $xml->offers->addChild('offer') returns an error.
It's all wrong because I've got problem with handling namespaces in SimpleXML! Please help!
E.g. by using xpath the get the target/parent element.
<?php
$envelope = new SimpleXMLElement('<?xml version="1.0" encoding="ISO-8859-2"?>
<!DOCTYPE pasaz:Envelope SYSTEM "loadOffers.dtd">
<pasaz:Envelope xmlns:pasaz="http://schemas.xmlsoap.org/soap/envelope/">
<pasaz:Body>
<loadOffers xmlns="urn:ExportB2B">
<offers />
</loadOffers>
</pasaz:Body>
</pasaz:Envelope>');
$envelope->registerXPathNamespace('pasaz', 'http://schemas.xmlsoap.org/soap/envelope/');
$envelope->registerXPathNamespace('b2b', 'urn:ExportB2B');
$ns = $envelope->xpath('//pasaz:Body/b2b:loadOffers/b2b:offers');
if ( 0<count($ns) ) {
$offers = $ns[0];
$offers->a = 'abc';
$offers->x = 'xyz';
}
echo $envelope->asXml();
prints
<?xml version="1.0" encoding="ISO-8859-2"?>
<!DOCTYPE pasaz:Envelope SYSTEM "loadOffers.dtd">
<pasaz:Envelope xmlns:pasaz="http://schemas.xmlsoap.org/soap/envelope/">
<pasaz:Body>
<loadOffers xmlns="urn:ExportB2B">
<offers><a>abc</a><x>xyz</x></offers>
</loadOffers>
</pasaz:Body>
</pasaz:Envelope>

Categories