【问题标题】:How to sort xml based on attribute value如何根据属性值对xml进行排序
【发布时间】:2013-02-22 13:03:04
【问题描述】:
$books = new DOMDocument();
$books->load( 'books.xml' );
$id = $_GET['id'];  
$xml = '<?xml version="1.0" encoding="UTF-8"?>'; 
$xml .= '<results><course>'.$id.'</course>'; 
$xml .= '<books>';
$items = $books->getElementsByTagName("item");
foreach( $items as $item )
{ 
    $item_id = $item->getAttribute("id");
    if($id == $item_id){
      ....
    }
}
$xml .= '</books></results>'; 
header ("Content-Type:text/xml");
echo ($xml);

我上面的代码会返回我:

<results>
   <course>1111</course>
   <books>
      <isbn id="0134582667" common="10" before="4" same="1" after="5" total="248"/>
      ..... 
   </books>
</results>

此页面包含以下错误:

第 12 列第 772 行的错误:XML 声明仅在 文档的开头 下面是到第一个页面的渲染 错误。

【问题讨论】:

  • 在 Stack Overflow 上提问之前请始终先 Google 一下,这样会占用其他用户的时间。 php sort xml 的第一个结果包含完整的答案。谢谢!
  • 尝试该解决方案已经不起作用,这就是为什么在这里发布。
  • 然后添加该上下文并指定什么不起作用。不要只询问没有背景信息且没有参考原件的副本。
  • 似乎与stackoverflow.com/questions/14957449/… 完全相同。在那里查看我的答案。

标签: php xml


【解决方案1】:

你可以把你的项目放入一个数组中,然后对数组进行排序,就像这样......

books.xml

<?xml version="1.0"?>
<results>
   <course>1111</course>
   <books>
      <isbn id="0134582667" common="10" before="4" same="1" after="5" total="248">248</isbn>
      <isbn id="0134582667" common="10" before="4" same="1" after="5" total="3">3</isbn>
      <isbn id="0134582667" common="10" before="4" same="1" after="5" total="224">224</isbn>
      <isbn id="0134582667" common="10" before="4" same="1" after="5" total="25">25</isbn>
   </books>
</results>

test.php

$books = new DOMDocument();
$books->load( 'books.xml' );
$items = $books->getElementsByTagName("isbn");

$nodeArray = array();
foreach ($items as $item) {
    $nodeArray[$item->getAttribute('total')] = $item;
}
ksort($nodeArray);

echo "<pre>". print_r($nodeArray, true) ."</pre>";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多