How to Return XML Results

Up until this point, you've been returning results in JSON format. Sometimes you might want to return results in XML format. You might do this because the consuming program for your web service can handle XML easier than JSON or because the person requesting the web service just wants XML.

The listing shows the date web service with XML output instead of JSON.

<?php
 
$friendlyDate = date("M d, Y","1369739047");
$unixTime = 1369739047;
$month = date("M","1369739047");
$dayOfWeek = date("l","1369739047");
$year = date("Y","1369739047");
 
$returnData = array(
        "friendlyDate" => $friendlyDate,
        "unixTime" => $unixTime,
        "monthNum" => $month,
        "dayOfWeek" => $dayOfWeek,
        "yearNum" => $year
);
 
$xml = new DOMDocument();
 
$dateInfoElement = $xml->createElement("dateInformation");
foreach ($returnData as $key => $value) {
    $xmlNode = $xml->createElement($key,$value);
    $dateInfoElement->appendChild($xmlNode);
}
$xml->appendChild($dateInfoElement);        
$header = "Content-Type:text/xml";
 
header($header);
print $xml->saveXML();
 
?>

The primary changes for the web service are to create an XML document. This is done through the DOMDocument object, which is part of PHP. With a new DOMDocument object instantiated, the next step is to create XML elements for each of the parts that you want to return. Wrap elements inside of a parent element called dateInformation. Doing so keeps the XML formatted properly.

The actual data for output is easy to make into XML. Because you have an array of date elements already, you can loop through that with a foreach() loop and run the createElement and appendChild methods.

The end result of your efforts is XML that looks like this:

<dateInformation>
<friendlyDate>May 28, 2013</friendlyDate>
<unixTime>1369739047</unixTime>
<monthNum>May</monthNum>
<dayOfWeek>Tuesday</dayOfWeek>
<yearNum>2013</yearNum>
</dateInformation>
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.