How to work with simple xml object in PHP

Ok, I have this php page that makes a searchItem request on amazon and returns a list of products.

when I use the following code, when I visit the page, I see an xml-formatted page (e.g. firefox):

<?php
  //in top of file: 
  header('Content-type: text/xml');

  // code 
  // code

  $response = file_get_contents($SignedRequest);  //doesn't matter what signerrequest is, it works
  print $response;
?>

Using this code above, I get a good XML file. However, I want the xml object in my PHP code to go in, etc. Therefore, I am trying to use the simplexml_load_string () function as follows:

$response = file_get_contents($SignedRequest);
$xml = simplexml_load_string($response); 

Now I want this object to print pretty nicely to see the xml structure. Some kind of cycle or something?

How can I see if I have an xml object and its structure, etc. Is there any printprint function for simplexmlobjects?

+3
source share
1 answer

. XML , . : http://gdatatips.blogspot.com/2008/11/xml-php-pretty-printer.html

<?php
/** Prettifies an XML string into a human-readable and indented work of art
 *  @param string $xml The XML as a string
 *  @param boolean $html_output True if the output should be escaped (for use in HTML)
 */
function xmlpp($xml, $html_output=false) {

   $xml_obj = new SimpleXMLElement($xml);
   $level = 4;
   $indent = 0; // current indentation level
   $pretty = array();

   // get an array containing each XML element
   $xml = explode("\n", preg_replace('/>\s*</', ">\n<", $xml_obj->asXML()));

   // shift off opening XML tag if present
   if (count($xml) && preg_match('/^<\?\s*xml/', $xml[0])) {
      $pretty[] = array_shift($xml);
   }

   foreach ($xml as $el) {
      if (preg_match('/^<([\w])+[^>\/]*>$/U', $el)) {
          // opening tag, increase indent
          $pretty[] = str_repeat(' ', $indent) . $el;
          $indent += $level;
      } else {
          if (preg_match('/^<\/.+>$/', $el)) {            
              $indent -= $level;  // closing tag, decrease indent
          }
          if ($indent < 0) {
              $indent += $level;
          }
          $pretty[] = str_repeat(' ', $indent) . $el;
      }
   }   
   $xml = implode("\n", $pretty);   
   return ($html_output) ? htmlentities($xml) : $xml;
}
$xml = file_get_contents('graph/some_xml_file.xml');
echo '<pre>' . xmlpp($xml, true) . '</pre>';
?>
+1

All Articles