O'Reilly logo

PHP Web Services by Lorna Jane Mitchell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 8. XML

XML is another very common data format used with APIs, and it feels familiar to us as developers. Anyone who has spent much time with the web will understand the “pointy brackets” style of XML and be able to read it. XML is a rather verbose format, the additional punctuation and scope for attributes as well as character data and nested tags can make for a large data size.

XML has many more features than JSON, and can represent a great many more things. You’ll see more of this in the chapter on SOAP, where complex data types and namespaces will come into play.

XML doesn’t have to be complicated though, we can easily represent simple data too, just as we did with JSON. Consider our shopping list again:

  • eggs
  • bread
  • milk
  • bananas
  • bacon
  • cheese

The XML representation of this list would be:

<?xml version="1.0"?>
<list>
  <item>eggs</item>
  <item>bread</item>
  <item>milk</item>
  <item>bananas</item>
  <item>bacon</item>
  <item>cheese</item>
</list>

Working with XML in PHP isn’t as easy as working with JSON. To produce the example above, the following code was used:

an example of working with XML

<?php

$list = array(
        "eggs",
        "bread",
        "milk",
        "bananas",
        "bacon",
        "cheese"
);

$xml = new SimpleXMLElement("<list />");
foreach($list as $item) {
    $xml->addChild("item", $item);
}

// for nice output
$dom = dom_import_simplexml($xml)->ownerDocument;
$dom->formatOutput = true;
echo $dom->saveXML();

We start out with the array that will be our list, then we instantiate a SimpleXMLElement object ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required