How to return value in XML format
Posted: Wed Jan 11, 2012 8:49 am
Hi all I have one question how can I send data result in XML format from PHP. For example you know that if you want you can use echo json_encode to send in json format is there something similar for XML.
I have found this example for representing data in browser...I just wanna send it back to another programming language, if I would be precise in QT. And there I would open that format and make what I need.
Here is example:
I have found this example for representing data in browser...I just wanna send it back to another programming language, if I would be precise in QT. And there I would open that format and make what I need.
Here is example:
Code: Select all
<?php
//simulate a remote connection
//include any libraries you want to use here.
//get the $mode var
//Set the content-type header to xml
header("Content-type: text/xml");
//echo the XML declaration
echo chr(60).chr(63).'xml version="1.0" encoding="utf-8" '.chr(63).chr(62);
?>
<xmlresponse>
<?php
//make a decision based on $mode
// switch ($mode) {
// case 'getitems':
//set items in a test array
$items_array[] = array(
'id'=>15,
'name'=>'Finger Bun',
'price'=>'$0.80 ea'
);
$items_array[] = array(
'id'=>16,
'name'=>'Donuts',
'price'=>'$0.50 ea'
);
$items_array[] = array(
'id'=>17,
'name'=>'Apple Pie',
'price'=>'$1.20 slice'
);
$items_array[] = array(
'id'=>18,
'name'=>'Double Choc Chip Cup Cakes',
'price'=>'$1.00 ea'
);
//echo a count of items
echo '<item_count>'.count($items_array).'</item_count>';
//echo the array in XML style
for ($x=0;$x<count($items_array);$x++) {
echo '<item>';
echo '<id>'.htmlspecialchars($items_array[$x]['id']).'</id>';
echo '<name>'.htmlspecialchars($items_array[$x]['name']).'</name>';
echo '<price>'.htmlspecialchars($items_array[$x]['price']).'</price>';
echo '</item>';
}
//} //end switch
?>
</xmlresponse>