使用PHP按一个节点按字母顺序对XML行进行排序

时间:2016-07-29 15:00:06

标签: php xml sorting alphabetical

这是我的XML示例:

<ROW>
<DEPT_CODE>11111</DEPT_CODE>
<DEPARTMENT>Program Name</DEPARTMENT>
<BLDG_CODE>BLCG</BLDG_CODE>
<ADDR_STREET1>123 Main Street</ADDR_STREET1>
<ADDR_STREET2>Suite 456</ADDR_STREET2>
<ADDR_STREET3>Lower Level</ADDR_STREET3>
<ADDR_CITY>New York</ADDR_CITY>
<ADDR_STATE>NY</ADDR_STATE>
<ADDR_ZIP>101010</ADDR_ZIP>
<PHONE>212-555-1234</PHONE>
<FAX>212-555-5678</FAX>
<EMAIL>email@company.com</EMAIL>
<URL>http://www.company.com</URL>
</ROW>

这是我的PHP:

<?php
$xml = simplexml_load_file('department.xml');
foreach($xml->children() as $depts) {
echo $depts->DEPARTMENT . "<br />";
}
?>

它按照它们出现在XML中的顺序正确输出部门列表,但我希望它按DEPARTMENT节点对alpha进行排序。

3 个答案:

答案 0 :(得分:0)

如果所有DEPARTMENTs都是唯一的,请执行:

<?php
$xml = simplexml_load_file('department.xml');
foreach($xml->children() as $depts) {
  $collect[(string)$depts->DEPARTMENT]=$depts;
}
ksort($collect);
foreach($collect as $depts) {
  echo $depts->DEPARTMENT . "<br />";
}
?>

答案 1 :(得分:0)

我不认为该示例与您的XML匹配。它只包含一个ROW,所以对它进行排序是没有意义的。让我们说你有类似的东西:

<records>
  <ROW>
    <DEPT_CODE>11111</DEPT_CODE>
    <DEPARTMENT>Program Name DEF</DEPARTMENT>
  </ROW>
  <ROW>
    <DEPT_CODE>12222</DEPT_CODE>
    <DEPARTMENT>Program Name ABC</DEPARTMENT>
  </ROW>
</records>

您需要先获取所有ROW个元素。 SimpleXML增加了许多接口和语法魔法。但是SimpleXMLElement::xpath()可以返回一个对象数组。获得数组后,您可以使用uasort()对比较函数进行排序。

$records = simplexml_load_string($xml);
$list = $records->xpath('/*/ROW');
uasort(
  $list,
  function($one, $two) {
    return strcasecmp($one->DEPARTMENT, $two->DEPARTMENT);
  } 
);

var_dump($list);

输出:

array(2) {
  [1]=>
  object(SimpleXMLElement)#3 (2) {
    ["DEPT_CODE"]=>
    string(5) "12222"
    ["DEPARTMENT"]=>
    string(16) "Program Name ABC"
  }
  [0]=>
  object(SimpleXMLElement)#2 (2) {
    ["DEPT_CODE"]=>
    string(5) "11111"
    ["DEPARTMENT"]=>
    string(16) "Program Name DEF"
  }
}

btw 在DOM中,它看起来像这样:

$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);
$list = iterator_to_array($xpath->evaluate('/*/ROW'));
uasort(
  $list,
  function($one, $two) use ($xpath) {
    return strcasecmp(
      $xpath->evaluate('string(DEPARTMENT)', $one), 
      $xpath->evaluate('string(DEPARTMENT)', $two)
    );
  } 
);

var_dump($list);

答案 2 :(得分:0)

以上所有答案似乎都显示了我最终得到的结果,但我正在添加最终结果以防其他人有用:

$xml = simplexml_load_file('data.xml');
foreach($xml->children() as $departments) {
    (string)$collect[(string)$departments->DEPT_NAME]=$departments;
}

usort ($collect, function($a, $b) {
    return strcmp($a->DEPT_NAME, $b->DEPT_NAME);
});

echo "<ul>";
    foreach($collect as $departments) {
        if ($departments->DEPT_NAME != "") {
            echo "<li>" . $departments->DEPT_NAME . "</li>";
        }
    }
echo "</ul>";