irwan

Creating XML Documents in PHP

Apr 22nd, 2012
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 9.26 KB | None | 0 0
  1. There's lots of reasons why you'd want to make XML documents using PHP. Maybe you're writing your own RSS feed or implementing a REST service. Whatever the reason, this tutorial will introduce you to the DOMDocument object and how to use it to create dynamic XML documents.
  2.  
  3. Before we start creating some actual XML, we're going to need something to make it from. I'm going to start by declaring a class that will hold some information about recent tutorials here at Switch On The Code. We'll take a collection of these objects and produce the same XML that is parsed by jQuery in a previous tutorial.
  4.  
  5. class Tutorial
  6. {
  7.   public $author;
  8.   public $title;
  9.   public $date;
  10.   public $categories;
  11.  
  12.   function __construct(
  13.     $author, $title, $date, $categories)
  14.   {
  15.     $this->author = $author;
  16.     $this->title = $title;
  17.     $this->date = $date;
  18.     $this->categories = $categories;
  19.   }
  20. }
  21.  
  22. Here we have a very simple PHP object that holds various pieces of information about a tutorial - author, title, publish date, and categories. Let's populate an array of four of these objects that we'll then convert to XML.
  23.  
  24. $tutorials = array(
  25.   new Tutorial(
  26.     "The Reddest",
  27.     "Silverlight and the Netflix API",
  28.     "1/13/2009",
  29.     array(
  30.       "Tutorials",
  31.       "Silverlight 2.0",
  32.       "Silverlight",
  33.       "C#",
  34.       "XAML"
  35.     )
  36.   ),
  37.    
  38.   new Tutorial(
  39.     "The Hairiest",
  40.     "Cake PHP 4 - Saving and Validating Data",
  41.     "1/12/2009",
  42.     array(
  43.       "Tutorials",
  44.       "CakePHP",
  45.       "PHP"
  46.     )
  47.   ),
  48.  
  49.   new Tutorial(
  50.     "The Tallest",
  51.     "Silverlight 2 - Using initParams",
  52.     "1/6/2009",
  53.     array(
  54.       "Tutorials",
  55.       "Silverlight 2.0",
  56.       "Silverlight",
  57.       "C#",
  58.       "HTML"
  59.     )
  60.   ),
  61.  
  62.   new Tutorial(
  63.     "The Fattest",
  64.     "Controlling iTunes with AutoHotkey",
  65.     "12/12/2008",
  66.     array(
  67.       "Tutorials",
  68.       "AutoHotkey",
  69.     )
  70.   )
  71. );
  72.  
  73. Now we're into the meat of the tutorial - actually building some XML.
  74.  
  75. header("Content-Type: text/plain");
  76.  
  77. //create the xml document
  78. $xmlDoc = new DOMDocument();
  79.  
  80. //create the root element
  81. $root = $xmlDoc->appendChild(
  82.           $xmlDoc->createElement("RecentTutorials"));
  83.        
  84. //make the output pretty
  85. $xmlDoc->formatOutput = true;
  86.  
  87. echo $xmlDoc->saveXML();
  88.  
  89. The first line just tells browsers that I'm not returning HTML, I'm simply returning plain text. This prevents them from trying to render our XML as HTML, which usually doesn't work and gives you a blank screen. I then create an instance of DOMDocument. The constructor takes in an optional version and encoding, but it defaults to "1.0", which works for me. Next I create the root node, which in my case is RecentTutorials. I do this by creating an element using DOMDocument's createElement function and append it as a child to the XML document. Now I simply tell the DOMDocument to format the output, which makes it pretty, and echo it to the display. If we run this script right now, we'd end up with this:
  90.  
  91. <?xml version="1.0"?>
  92. <RecentTutorials/>
  93.  
  94. Now let's start populating our XML with some information about tutorials. We'll start by simply creating a Tutorial tag and displaying the author as an attribute and the title and date as child elements.
  95.  
  96. foreach($tutorials as $tut)
  97. {
  98.   //create a tutorial element
  99.   $tutTag = $root->appendChild(
  100.               $xmlDoc->createElement("Tutorial"));
  101.            
  102.   //create the author attribute
  103.   $tutTag->appendChild(
  104.     $xmlDoc->createAttribute("author"))->appendChild(
  105.       $xmlDoc->createTextNode($tut->author));
  106.  
  107.   //create the title element
  108.   $tutTag->appendChild(
  109.     $xmlDoc->createElement("Title", $tut->title));
  110.  
  111.   //create the date element
  112.   $tutTag->appendChild(
  113.     $xmlDoc->createElement("Date", $tut->date));
  114. }
  115.  
  116. I first create a tag for the tutorial the same way as I made the root tag, except now I added it as a child to the root element instead of the XML document. Unfortunately, unlike createElement, createAttribute doesn't have the ability to take the value in the constructor. This means we have to use some very verbose syntax to get an attribute added to an element. First we call createAttribute and pass it the name we want, then we have to append the value of the attribute as a child by calling createTextNode and passing it the value. Once we have the attribute created, we simply append it as a child to the tutorial tag. Lastly we add elements for the title and date by calling createElement and passing in the names and values. Now we've got something that looks like this:
  117.  
  118. <?xml version="1.0"?>
  119. <RecentTutorials>
  120.   <Tutorial author="The Reddest">
  121.     <Title>Silverlight and the Netflix API</Title>
  122.     <Date>1/13/2009</Date>
  123.   </Tutorial>
  124.   <Tutorial author="The Hairiest">
  125.     <Title>Cake PHP 4 - Saving and Validating Data</Title>
  126.     <Date>1/12/2009</Date>
  127.   </Tutorial>
  128.   <Tutorial author="The Tallest">
  129.     <Title>Silverlight 2 - Using initParams</Title>
  130.     <Date>1/6/2009</Date>
  131.   </Tutorial>
  132.   <Tutorial author="The Fattest">
  133.     <Title>Controlling iTunes with AutoHotkey</Title>
  134.     <Date>12/12/2008</Date>
  135.   </Tutorial>
  136. </RecentTutorials>
  137.  
  138. All that's left to add now are the categories. We've actually already seen everything we'll need to display them, so it's just a matter of looping through them and adding elements to the document.
  139.  
  140. //create the categories element
  141. $catTag = $tutTag->appendChild(
  142.             $xmlDoc->createElement("Categories"));
  143.  
  144. //create a category element for each category in the array
  145. foreach($tut->categories as $cat)
  146. {
  147.   $catTag->appendChild(
  148.     $xmlDoc->createElement("Category", $cat));
  149. }
  150.  
  151. And there you have it. Now we've got our complete XML document.
  152.  
  153. <?xml version="1.0"?>
  154. <RecentTutorials>
  155.   <Tutorial author="The Reddest">
  156.     <Title>Silverlight and the Netflix API</Title>
  157.     <Date>1/13/2009</Date>
  158.     <Categories>
  159.       <Category>Tutorials</Category>
  160.       <Category>Silverlight 2.0</Category>
  161.       <Category>Silverlight</Category>
  162.       <Category>C#</Category>
  163.       <Category>XAML</Category>
  164.     </Categories>
  165.   </Tutorial>
  166.   <Tutorial author="The Hairiest">
  167.     <Title>Cake PHP 4 - Saving and Validating Data</Title>
  168.     <Date>1/12/2009</Date>
  169.     <Categories>
  170.       <Category>Tutorials</Category>
  171.       <Category>CakePHP</Category>
  172.       <Category>PHP</Category>
  173.     </Categories>
  174.   </Tutorial>
  175.   <Tutorial author="The Tallest">
  176.     <Title>Silverlight 2 - Using initParams</Title>
  177.     <Date>1/6/2009</Date>
  178.     <Categories>
  179.       <Category>Tutorials</Category>
  180.       <Category>Silverlight 2.0</Category>
  181.       <Category>Silverlight</Category>
  182.       <Category>C#</Category>
  183.       <Category>HTML</Category>
  184.     </Categories>
  185.   </Tutorial>
  186.   <Tutorial author="The Fattest">
  187.     <Title>Controlling iTunes with AutoHotkey</Title>
  188.     <Date>12/12/2008</Date>
  189.     <Categories>
  190.       <Category>Tutorials</Category>
  191.       <Category>AutoHotkey</Category>
  192.     </Categories>
  193.   </Tutorial>
  194. </RecentTutorials>
  195.  
  196. And just so you can see everything in one place, here is the final content of the PHP script:
  197.  
  198. class Tutorial
  199. {
  200.   public $author;
  201.   public $title;
  202.   public $date;
  203.   public $categories;
  204.  
  205.   function __construct(
  206.     $author, $title, $date, $categories)
  207.   {
  208.     $this->author = $author;
  209.     $this->title = $title;
  210.     $this->date = $date;
  211.     $this->categories = $categories;
  212.   }
  213. }
  214.  
  215. //make some tutorial objects
  216. $tutorials = array(
  217.   new Tutorial(
  218.     "The Reddest",
  219.     "Silverlight and the Netflix API",
  220.     "1/13/2009",
  221.     array(
  222.       "Tutorials",
  223.       "Silverlight 2.0",
  224.       "Silverlight",
  225.       "C#",
  226.       "XAML"
  227.     )
  228.   ),
  229.    
  230.   new Tutorial(
  231.     "The Hairiest",
  232.     "Cake PHP 4 - Saving and Validating Data",
  233.     "1/12/2009",
  234.     array(
  235.       "Tutorials",
  236.       "CakePHP",
  237.       "PHP"
  238.     )
  239.   ),
  240.  
  241.   new Tutorial(
  242.     "The Tallest",
  243.     "Silverlight 2 - Using initParams",
  244.     "1/6/2009",
  245.     array(
  246.       "Tutorials",
  247.       "Silverlight 2.0",
  248.       "Silverlight",
  249.       "C#",
  250.       "HTML"
  251.     )
  252.   ),
  253.  
  254.   new Tutorial(
  255.     "The Fattest",
  256.     "Controlling iTunes with AutoHotkey",
  257.     "12/12/2008",
  258.     array(
  259.       "Tutorials",
  260.       "AutoHotkey",
  261.     )
  262.   )
  263. );
  264.  
  265. //create the xml document
  266. $xmlDoc = new DOMDocument();
  267.  
  268. //create the root element
  269. $root = $xmlDoc->appendChild(
  270.           $xmlDoc->createElement("RecentTutorials"));
  271.        
  272.  
  273. foreach($tutorials as $tut)
  274. {
  275.   //create a tutorial element
  276.   $tutTag = $root->appendChild(
  277.               $xmlDoc->createElement("Tutorial"));
  278.            
  279.   //create the author attribute
  280.   $tutTag->appendChild(
  281.     $xmlDoc->createAttribute("author"))->appendChild(
  282.       $xmlDoc->createTextNode($tut->author));
  283.    
  284.   //create the title element
  285.   $tutTag->appendChild(
  286.     $xmlDoc->createElement("Title", $tut->title));
  287.    
  288.   //create the date element
  289.   $tutTag->appendChild(
  290.     $xmlDoc->createElement("Date", $tut->date));
  291.  
  292.   //create the categories element
  293.   $catTag = $tutTag->appendChild(
  294.               $xmlDoc->createElement("Categories"));
  295.  
  296.   //create a category element for each category in the array
  297.   foreach($tut->categories as $cat)
  298.   {
  299.     $catTag->appendChild(
  300.       $xmlDoc->createElement("Category", $cat));
  301.   }
  302. }
  303.  
  304. header("Content-Type: text/plain");
  305.  
  306. //make the output pretty
  307. $xmlDoc->formatOutput = true;
  308.  
  309. echo $xmlDoc->saveXML();
Advertisement
Add Comment
Please, Sign In to add comment