How to return value in XML format

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
denonth
Forum Newbie
Posts: 10
Joined: Tue Jan 10, 2012 1:26 pm

How to return value in XML format

Post by denonth »

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:

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>
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: How to return value in XML format

Post by Christopher »

You might want to look at SimpleXML (http://us.php.net/manual/en/book.simplexml.php).
(#10850)
Post Reply