50% OFF!!!

Friday, November 13, 2015

PHP | XML to Html Table elment convertion

In this thread,
I will show generic & universal function that
gets XML string,
convert it,
and display it as an HTML table.
(you can add any css style to design your table later on of course)

The following code is using XML example from http://www.w3schools.com/xml/simple.xml.
The XML looks like that:
    <name>Belgian Waffles</name>
    <description>Two of our famous...</description>
    <name>Strawberry Belgian Waffles</name>
    <description>Light Belgian waffles...</description>
    <name>Berry-Berry Belgian Waffles</name>
    <description>Light Belgian....</description>
    <name>French Toast</name>
    <description>Thick slices made....</description>
    <name>Homestyle Breakfast</name>
    <description>Two eggs, bacon...</description>

The function xmlToHtmlTable 
gets a SimpleXMLElement parameter which points to main parent for which will print all his children,
and returns html table representing the XML as string.

The Code:
 // get XML remotely / locally / or / just set it as string '<root>...</root>'  
 $sXml = file_get_contents('http://www.w3schools.com/xml/simple.xml');  
 // parse XML  
 $oXML = simplexml_load_string($sXml);  
 if (!$oXML) {  
      die('xml format not valid or simplexml module missing.');  
 // assuming running the root  
 $oXmlRoot = $oXML; // or can be [$oXML->food]  
 //echo '<pre>'; print_r( $oXmlRoot ); echo '</pre>';  
 echo xmlToHtmlTable($oXmlRoot);  
 function xmlToHtmlTable($p_oXmlRoot) {  
      $bIsHeaderProceessed = false;  
      $sTHead = '';  
      $sTBody = '';       
      foreach ($p_oXmlRoot as $oNode) {  
           $sTBody .= '<tr>';  
           foreach ($oNode as $sName => $oValue){  
                if (!$bIsHeaderProceessed) {  
                     $sTHead .= "<th>{$sName}</th>";  
                $sValue = (string)$oValue;  
                $sTBody .= "<td>{$sValue}</td>";                 
           $bIsHeaderProceessed = true;  
           $sTBody .= '</tr>';  
      $sHTML = "<table border=1>  
      return $sHTML;  

This will output:

Hope it helps!


No comments:

Post a Comment