开发者

How to work with simple xml object in PHP

开发者 https://www.devze.com 2023-02-17 17:37 出处:网络
Ok, I have this php page that makes an searchItem request at amazon and gets back a list of products.

Ok, I have this php page that makes an searchItem request at amazon and gets back a list of products.

when i use the following code, when visiting the page I see a xml formatted page (like firefox does):

<?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 $respon开发者_开发技巧se;
?>

Using this code above I get a good xml file. However I want an xml object in my php code to traverse in etc. So i try using the simplexml_load_string() function like this:

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

I now want sort of pretty print this object to see the xml structure. Some loop or something?

How can I see whether I have an xml object and what it's structure is etc. Is there some kind of prettyprint function for simplexmlobjects?


You can try this function. I've already tested it on an xml file and it works. Originally done by Eric from this post: 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>';
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消