XML/PHP: XML doesnt get written properly by my script - php

I seem to have a small problem, whenever i insert information via a form into my XML file, it adds the information directly IN the previous's entry's child, instead of creating a new child, for the entry, i get something like THIS:
<people>
<person>
<name>Lighty</name>
<age>17</age>
<sex>M</sex>
<comment>iets</comment>
<name>Darky</name><age>22</age><sex>F</sex><comment>things</comment></person>
While i need to have something, that would look like THIS:
<people>
<person>
<name>Lighty</name>
<age>17</age>
<sex>M</sex>
<comment>iets</comment>
</person>
<person>
<name>Darky</name>
<age>22</age>
<sex>F</sex>
<comment>iets</comment>
</people>
i tried using the "$xml->formatOutput = true;" line, but it would just add the child formatOutput with 1 filled in, a complete fail.
Any idea what im doing wrong? here is m PHP Code:
<?php
echo ('Script started');
//making sure the script only runs when you use a post
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo ('-Post accepted');
//Load XML File into variable
$xml = simplexml_load_file("phptest3.xml");
echo ('-XML Loaded');
//Connect form to Variables
$name = $_POST['name'];
$age = $_POST['age'];
$sex = $_POST['sex'];
$comment = $_POST['comment'];
echo ('-Vars connected');
//Function to strip items that are not needed to prevend XSS/Injections
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
echo ('-Injections stripped');
//Create new children in XML file and Connect the from data to the corresponding XML entries
$xml->formatOutput = true;
$xml->people[0];
$xml->people->addChild('person');
$xml->person->addChild('name', $name);
$xml->person->addChild('age', $age);
$xml->person->addChild('sex', $sex);
$xml->person->addChild('comment', $comment);
echo ('-Data inserted');
//Save current data to XML file...
$xml->savexml('phptest3.xml');
echo ('-saved');
}
echo ('-Script ended.');
?>

You can do this with a combination of SimpleXMLElement and DOMDocument.
This is how I did it:
<pre>
<?php
// Orignal XML - Starting Empty
$xmlStr = "<?xml version='1.0' standalone='yes'?>
<people></people>";
// Load XML
$people = new SimpleXMLElement($xmlStr);
// Debug (Before Add)
echo "<b>Before</b> Add\r\n";
print_r($people);
echo "<hr>\r\n\r\n";
// Add First Person
$newPerson = $people->addChild('person');
$newPerson->addChild('name', 'Lighty');
$newPerson->addChild('age', 17);
$newPerson->addChild('sex', 'M');
$newPerson->addChild('comment', 'iets');
// Debug (After Add)
echo "<b>After</b> Add\r\n";
print_r($people);
echo "<hr>\r\n\r\n";
// Output Modified XML With Formatting
$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->loadXML($people->asXML());
$dom->formatOutput = true;
echo $dom->saveXml();
?>
Browser Outout:
Formatted XML Output:
<?xml version="1.0" standalone="yes"?>
<people>
<person>
<name>Lighty</name>
<age>17</age>
<sex>M</sex>
<comment>iets</comment>
</person>
</people>
Hope this helps.

Related

append XML tree as child to another XML, using PHP

I want to add an XML tree into another XML, and I have tried with following code which is not working:
<?php
$str1 = '<parent>
<name>mrs smith</name>
</parent>';
$xml1 = simplexml_load_string($str1);
print_r($xml1);
$str2 = '<tag>
<child>child1</child>
<age>3</age>
</tag>';
$xml2 = simplexml_load_string($str2);
print_r($xml2);
$xml1->addChild($xml2);
print_r($xml1);
?>
Expect output XML:
<parent>
<name>mrs smith</name>
<tag>
<child>child1</child>
<age>3</age>
</tag>
</parent>
Please assist me.
You can use DOMDocument::importNode
<?php
$str2 = '<tag>
<child>child1</child>
<age>3</age>
</tag>';
$str1 = '<parent>
<name>mrs smith</name>
</parent>';
$tagDoc = new DOMDocument;
$tagDoc->loadXML($str2);
$tagNode = $tagDoc->getElementsByTagName("tag")->item(0);
//echo $tagDoc->saveXML();
$newdoc = new DOMDocument;
$newdoc->loadXML($str1);
$node = $newdoc->importNode($tagNode, true);
$newdoc->documentElement->appendChild($node);
echo $newdoc->saveXML();die;

PHP - Generate XML in loop using DOM library

I'm retrieving a set of contact records from a database query, and I then need to generate an XML response that is returned to the browser.
The PHP loop that retrieves the records looks like this:
foreach($contacts as $contact){
$firstName = $record->getField('first') ;
$lastName = $record->getField('last') ;
$recnum++; }
and the XML I need to generate looks like this:
<?xml version="1.0" encoding="utf-8"?>
<contacts>
<contact>
<first_name>Penny</first_name>
<last_name>Lancaster</last_name>
</contact>
<contact>
<first_name>Geoff</first_name>
<last_name>McDermott</last_name>
</contact>
</contacts>
I've been able to create a single hardcoded XML response before using:
$doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
$root = $doc->createElement('error');
$doc->appendChild($root);
$desc = $doc->createElement('description', $error);
$root->appendChild($desc);
echo $doc->saveXML();
but I can't work out the syntax to incorporate this into a loop and generate the XML dynamically.
It's pretty simple:
$doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
$contactsElement = $doc->createElement('contacts');
foreach($contacts as $contact){
// your loop, is working? What is $record?
$firstName = $record->getField('first') ;
$lastName = $record->getField('last') ;
$recnum++; // is useful for something?
$contactElement = $doc->createElement('contact');
$firstNameElement = $doc->createElement('first_name', $firstName);
$lastNameElement = $doc->createElement('last_name', $lastName);
$contactElement->appendChild($firstNameElement);
$contactElement->appendChild($lastNameElement);
$contactsElement->appendChild($contactElement);
}
echo $doc->saveXML();

Generate XML using 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.

How to delete and edit specific xml node using PHP?

I am practicing on XML and PHP. I can not find out how to delete the whole xml node. Here is my XML:
<?xml version="1.0" encoding="UTF-8"?>
<items>
<playlist_name>Channel List</playlist_name>
<category>
<category_id>1</category_id>
<category_title>HD</category_title>
</category>
<channel>
<title>VTC HD1</title>
<stream_url><![CDATA[http://203.162.16.22:80/lives/origin01/vtchd1.isml/vtchd1.m3u8]]></stream_url>
<logo_30x30>vtchd1.jpg</logo_30x30>
<category_id>1</category_id>
</channel>
<channel>
<title>VTC HD2</title>
<stream_url><![CDATA[http://203.162.16.22:80/lives/origin01/vtchd2.isml/vtchd2.m3u8]]></stream_url>
<logo_30x30>vtchd2.jpg</logo_30x30>
<category_id>1</category_id>
</channel>
</items>
And here is the code of two function which I am having problem, delete() and edit()
<?php
function delete_channel()
{
$file = "nStream.xml";
$fp = fopen($file, "rb") or die("cannot open file");
$str = fread($fp, filesize($file));
$xml = new DOMDocument();
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->loadXML($str) or die("Error");
// original
// echo "<xmp>OLD:\n". $xml->saveXML() ."</xmp>";
// get document element
$root = $xml->documentElement;
$fnode = $root->firstChild;
//get a node
$ori = $fnode->childNodes->item(0);
// remove
$fnode->removeChild($ori);
// echo "<xmp>NEW:\n". $xml->saveXML() ."</xmp>";
}
function edit_channel()
{
echo 'Go Edit';
}
For the delete_channel(), nothing is deleted when I run that function. I want each time I use that function, one in xml file ll be deleted.
delete a <channel> with simplexml:
$xml = simplexml_load_file($filename);
// select the channel to be deleted by title
$channel = $xml->xpath("//channel[title='VTC HD2']");
// delete it!
unset($channel[0][0]);
// save it
$xml->asXML($filename);
see it working: https://eval.in/37084

XML Parsing Error

here i am creating xml file dynamically at run time but i m getting error
XML Parsing Error: junk after document element
Location: http://localhost/tam/imagedata.php?imageid=8
Line Number 9, Column 1:
^
$id=$_GET['imageid'];
$dom = new DomDocument('1.0');
$query="select * from tbl_image_gallery where imageId='$id'";
$select=mysql_query($query);
while($res=mysql_fetch_array($select))
{
$content = $dom->appendChild($dom->createElement('content'));
$image = $content->appendChild($dom->createElement('image'));
$small_image_path = $image->appendChild($dom->createElement('small_image_path'));
$small_image_path->appendChild($dom->createTextNode("load/images/small/".$res['image']));
$big_image_path = $image->appendChild($dom->createElement('big_image_path'));
$big_image_path->appendChild($dom->createTextNode("load/images/big/".$res['image']));
$description = $image->appendChild($dom->createElement('description'));
$description->appendChild($dom->createTextNode($res['description']));
$dom->formatOutput = true;
}
echo $test1 = $dom->saveXML();
and xml format is
<?xml version="1.0"?>
<content>
<image>
<small_image_path>load/images/small/1.jpg</small_image_path>
<big_image_path>load/images/big/1.jpg</big_image_path>
<description>hgjghj</description>
</image>
<image><small_image_path>load/images/small/2.jpg</small_image_path><big_image_path>load/images/big/2.jpg</big_image_path><description>fgsdfg</description></image><image><small_image_path>load/images/small/3.jpg</small_image_path><big_image_path>load/images/big/3.jpg</big_image_path><description>sdfgsdfg</description></image><image><small_image_path>load/images/small/4.jpg</small_image_path><big_image_path>load/images/big/4.jpg</big_image_path><description>gsbhsg</description></image><image><small_image_path>load/images/small/4.jpg</small_image_path><big_image_path>load/images/big/4.jpg</big_image_path><description>gsbhsg</description></image><image><small_image_path>load/images/small/avatar.jpg</small_image_path><big_image_path>load/images/big/avatar.jpg</big_image_path><description></description></image></content>
Can it be that you are posting html code into the description field?
Could be usefull to add a CDataSection instead of a TextNode
$cdata = $dom->createCDATASection($res['description']);
$image->appendChild($cdata);

Categories