php - 如何在 PHP 中使用简单的 xml 对象

标签 php xml

好的,我有这个 php 页面,它在亚马逊上发出 searchItem 请求并返回产品列表。

当我使用以下代码时,在访问页面时我看到一个 xml 格式的页面(就像 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;
?>

使用上面的代码我得到了一个好的 xml 文件。但是我想要我的 php 代码中的一个 xml 对象遍历等等。所以我尝试像这样使用 simplexml_load_string() 函数:

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

我现在想要漂亮地打印此对象以查看 xml 结构。一些循环还是什么?

我如何查看我是否有 xml 对象及其结构等。是否有某种用于 simplexmlobjects 的 prettyprint 函数?

最佳答案

你可以试试这个功能。我已经在 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>';
?>

关于php - 如何在 PHP 中使用简单的 xml 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5364989/

相关文章:

php - Drupal Audio 带音频模块或其他

PHP/MySQL 关系数据库模式的搜索代码和逻辑

php - MySQL 查询中的组逗号分隔元素

php - 如何将 PHP 变量名传递给 Javascript 函数

java - Java中如何使用XPath检查节点是否具有一个或多个特定属性?

php - 显示名称中含有特殊字符 "$"或 "-"的变量

javascript - AJAX 多个输入不传递或发送数据到 PHP

java - 生成按钮的随机位置

xml - 如何使用 XSLT 获取 XML 属性的首字母?

sql-server - 在T-SQL中获取包含某个内部节点的所有XML节点