How to generate xml in codeigniter
Looks like you are developing an API. Why don't you use the RESTServer plugin for CodeIgniter?
It's all handled for you and you don't have to worry about the format. You can choose to output in JSON or XML.
Plugin developed by Phil: https://github.com/philsturgeon/codeigniter-restserver
I believe the most practical, logical and error free way to generate an XML is to create a DOMDocument
as suggested by Eineki in this answer, allowing the xmltree to be searched through an xpath query.
With this said, some years ago Dan Simmons created a single MY_xml_helper.php that you can just copy to your application/helpers
folder directly. Here's the entire code without comments:
Notice that you set the encoding like this: new DOMDocument('1.0', 'UTF-8');
. Here's an example:
$this->load->helper('xml');$dom = xml_dom();$book = xml_add_child($dom, 'book');xml_add_child($book, 'title', 'Hyperion');$author = xml_add_child($book, 'author', 'Dan Simmons'); xml_add_attribute($author, 'birthdate', '1948-04-04');xml_add_child($author, 'name', 'Dan Simmons');xml_add_child($author, 'info', 'The man that wrote MY_xml_helper'); xml_print($dom);
Would simply output:
<?xml version="1.0" encoding="UTF-8"?><book> <title>Hyperion</title> <author birthdate="1948-04-04"> <name>Dan Simmons</name> <info>The man that wrote MY_xml_helper</info> </author></book>
The xml_print
either echo
s or returns the $xml->saveXML()
.
Notice: you can still use the one and only function from the default XML helper from CodeIgniter: xml_convert("<title>'Tom' & \"Jerry\"")
which just outputs: <title>'Tom' & "Jerry"
.
Your XML document have to start with:
<?xml version="1.0"?>
no white symbols no "spaces" no "enters". Your document starts with line-break as the error message says:
Warning: simplexml_load_file() [function.simplexml-load-file]: http://mydeal.ge/api/xml:2: parser error : XML declaration allowed only at the start of the document in /home1/stinky/public_html/test.php on line 2
and delete spaces from this line:
$output .= "<sale id = '".$item->id."'>";$output .= "<sale id='".$item->id."'>";