按字段对远程XML文件进行排序

时间:2016-07-30 16:34:42

标签: php sorting simplexml

我需要对从远程服务器访问并通过simpleXML访问的XML文件进行排序(这是从提供程序访问规范中的文件的批准方式 - 因此无法更改)

$propertylist = simplexml_load_file("http://link.to/file.xml?accesskey");

我需要从$propertylist->price从高到低排序,而不将XML内容传递到单独的文件中

我已经看到(并尝试过)在这里发现的一些建议但没有成功:(

arsort($propertylist->price);打破了代码

以下是XML的摘录:

<?xml version="1.0" encoding="UTF-8"?>
<properties>
   .......
   <property>
      <propertyID />
      <branchID>1</branchID>
      <clientName>y</clientName>
      <branchName>z</branchName>
      <department>S</department>
      <referenceNumber>1</referenceNumber>
      <price>219950</price>
      <fullDescription><![CDATA[<strong>LOCATION</strong>]]></fullDescription>
      <flags>
         <flag />
      </flags>
      <images>
         <image modified="2014-05-22 11:10:33">http://link.to/image.jpg</image>
      </images>
      <epcFrontPages />
      <brochures>
         <brochure modified="2014-05-22 14:37:38">http://link.to/file.pdf</brochure>
      </brochures>
   </property>
   .......
</properties>

非常感谢任何帮助

2 个答案:

答案 0 :(得分:0)

请试试这个:

//Read the xml file
$xml = simplexml_load_file("http://link.to/file.xml?accesskey");
//Get all properties
$propertylist = $xml->xpath("/properties/property");
//Sort them by price (descending)
usort($propertylist, function($a, $b) {
    return $b->price - $a->price;
});

//Now you can loop through your ordered `$propertylist`:
foreach($propertylist as $property) {
    echo $property->fullDescription . "<br>";
}

演示: https://3v4l.org/Gj120

答案 1 :(得分:0)

控制您的数据到数组

<?php
$simple = "<para><note>simple note</note></para>";
$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
echo "Index array\n";
print_r($index);
echo "\nVals array\n";
print_r($vals);
?>

然后将其排序为数组 sort array functions