I know there are many examples of creating cdata with php but I have not found one that helps in my situation. I need to create an xml file that will be used by something other than php. I need to create cdata in the xml that will contain a function to be used. The final xml file should look as follows.
<?xml version="1.0" encoding="utf-8" ?>
<component name="Test" extends="out" >
<script type="text" >
<![CDATA[
function init()
m.content = createObject("RoSGNode","ContentNode")
m.top.setFocus(true)
dateNow = CreateObject("roDateTime")
dateNow = dateNow.asSeconds() - 2000
addItemName($Iname)
end function
]]>
</script>
</component>
Code to create the xml. I just don't know how to create cdata info. Any help would be greatly appreciated.
$xml=new DOMDocument('1.0', 'UTF-8');
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;
$components = $xml->createElement("components");
$name=$xml->createAttribute("name");
$name->value = "Test";
$extends=$xml->createAttribute("extends");
$extends->value = "out";
$components->appendChild($name);
$components->appendChild($extends);
$script = $xml->createElement("script");
$type=$xml->createAttribute("type");
$type->value = "text";
$script->appendChild($type);
$components->appendChild($script);
$xml->appendChild($components);
$xml->save($filename2);
After little more effort, was able to get cdata in.
$cdata = $xml->createCDATASection("function init()");
$script->appendChild($cdata);
Related
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.
I have this test.xml:
<?xml version="1.0"?>
<Images>
<Image>
<Id>765</Id>
<Title>Img title 1</Title>
<Name>some_path_to_img.jpg</Name>
</Image>
</Images>
I try to append new '<Image>' to '<Images>', but without success.
Here is my code:
function update_xml_file() {
$xml = new DOMDocument();
$xml->load(file_get_contents('test.xml'));
$xml->formatOutput = true;
$base_node = $xml->getElementsByTagName('Images')->item(0);
$newimage = $xml->createElement("Image");
$img_id = $xml->createElement("Id");
$img_title = $xml->createElement("Title");
$img_name = $xml->createElement("Name");
$img_id->nodeValue = '766';
$img_title->nodeValue = 'Image title 2';
$img_name->nodeValue = 'some_path_to_img2.jpg';
$newimage->appendChild($img_id);
$newimage->appendChild($img_title);
$newimage->appendChild($img_name);
$base_node->appendChild($newimage);
umask();
$xml->save("test.xml");
}
Looking around for related discussions didn't help me.
Thanks for your time.
You have a little typo in the code which loads the xml data.
Change it to:
$xml->loadXML(file_get_contents('test.xml'));
or ( better)
$xml->load('test.xml');
Refer to the documentation of DOMDocument::loadXML() and DOMDocument::load()
You can also use this package from github to make it simple http://github.com/toureiliass/xdt
You can do it in a few line of code
$con = new XDT();
$con->connect('test.xml');
$con->getDocumentRootElement()->append('<image><id>765</id><title>some title</title><name>some_path_to_image.jpg</name></image>');
$con->save();
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).
I am using XPath to query an xml document and then copy found nodes to a separate results xml file, however the problem I am having is that the XML declaration at the top gets added each time a new node is added to the results file.
Here is my php code:
$allEventsForVenue = $xPath->query(
"/Ticket/EventsPoints/Event[contains(PerformanceName,'$searchParam')]"
);
foreach ($allEventsForVenue as $event) {
$dstDom = new DOMDocument('1.0', 'utf-8');
$dstDom->appendChild($dstDom->createElement('EventsPoints'));
$dstDom->documentElement->appendChild($dstDom->importNode($event, true));
//echo $dstDom->saveXml();
$dstDom->formatOutput = true;
$strxml .= $dstDom->saveXML();
$handle = fopen("/var/www/html/xml/searchresults$searchID.xml", "w");
fwrite($handle, $strxml);
fclose($handle);
}
Invalid XML File (two xml declarations in the one file):
->> <?xml version="1.0" encoding="utf-8"?>
<EventsPoints>
<Event ID="17">
<PerformanceName>Bressie</PerformanceName>
<PresaleTime/>
<PriceRange>17 - 17</PriceRange>
<VenueID ID="19"/>
</Event>
</EventsPoints>
->> <?xml version="1.0" encoding="utf-8"?>
<EventsPoints>
<Event ID="180">
<PerformanceName>U2</PerformanceName>
<PriceRange>20 - 20</PriceRange>
<VenueID ID="198"/>
</Event>
</EventsPoints>
You are creating new DOMDocument instance in loop. Also you are writing in each iteration. This is making new XML document on each iteration and its get appended in your xml file. What you need to do is, loop the XML generation part. Not the whole thing.
If you loop only the appendChild parts, your problem will be solved.
$dstDom = new DOMDocument('1.0', 'utf-8');
$dstDom->formatOutput = true;
foreach ($allEventsForVenue as $event) {
$dstDom->appendChild($dstDom->createElement('EventsPoints'));
$dstDom->documentElement->appendChild($dstDom->importNode($event, true));
}
file_put_contents("/var/www/html/xml/searchresults$searchID.xml", $dstDom->saveXML());
DomDocument lets you output a specific node without the xml declaration.
Just include a node in saveXML, like saveXML($node), with node being an XMLNode type object.
With this method I think you can bypass the whole "create sub-xmldocument/import node" thing, by outputting directly the desired node in a string.
use something like this
enter <?php
// Continued from example XML above.
/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');
while(list( , $node) = each($result)) {
echo $node->asXML();
}
?>
Here is what i have as best i can figure what needs to be done. But im just at a loss as to how to get it to work.
Both $xml and $xmlfile are DOM objects/XML. $xml is the source of the data i want to append into $mxlfile.
$xml is sent in to the function from another function as a dom object.
This is how the xml comes to me.
<?xml version="1.0" encoding="utf-8"?>
<!-- Automatically generated data from EVE-Central.com -->
<!-- This is the new API :-) -->
<evec_api version="2.0" method="marketstat_xml">
<marketstat>
<type id="18">
<all>
<volume>1934078988.00</volume>
<avg>98.31</avg>
<max>26721.00</max>
<min>0.53</min>
<stddev>1339.78</stddev>
<median>26.31</median>
<percentile>0.00</percentile>
</all>
<buy>
<volume>1894081100.00</volume>
<avg>20.77</avg>
<max>31.31</max>
<min>0.53</min>
<stddev>7.25</stddev>
<median>26.00</median>
<percentile>28.17</percentile>
</buy>
<sell>
<volume>39997888.00</volume>
<avg>34.32</avg>
<max>26721.00</max>
<min>4.01</min>
<stddev>2339.28</stddev>
<median>29.80</median>
<percentile>26.76</percentile>
</sell>
</type>
<type id="ectera">
</type>
</marketstat>
</evec_api>
And here the part of my function i just cant get working.
$xml->preserveWhiteSpace = FALSE;
$xml->formatOutput = TRUE;
if(is_file($file)){
$xmlfile = new DOMDocument;
$xmlfile->load($file);
$dst = $xmlfile->getElementsByTagName('marketStat');
foreach($xml->getElementsByTagName('type') as $child){
$dst->appendChild($xmlfile->importNode($child));}
$xmlfile->save($file);
}
I know there's something wrong, but im just teaching myself xml and dom, so help would be much appreciated.
<?php
if(is_file($file))
{
$xmlfile = new DOMDocument;
$xml->preserveWhiteSpace = FALSE;
$xml->formatOutput = TRUE;
$xmlfile->load($file);
$dst = $xmlfile->getElementsByTagName('marketStat');
$parentLength = $dst->length;
for($i=0; $i< $parentLength ; $i++)
{
foreach($xmlfile->getElementsByTagName('type') as $child)
{
$dst->item($i)->appendChild($child);
}
}
$xmlfile->save($file);
}
Your code has two mistakes
You can set options for DOM parser after you create the document.
You can not use appendChild on list of DOM object. You have to add them on indivisual DOM element one by one.