如何在php中排序xml文件

时间:2023-01-15 09:27:30

I tried to sort my xml in php. I found a solution here: Sorting XML File into ascending order using php

我试图在php中对我的xml进行排序。我在这里找到了一个解决方案:使用php将XML文件按升序排序

However, if there are attributes like item 51390, which has 2 courses while others has got 1, the solution does display them all. Because in the array, he only insert

但是,如果有项目51390等属性,其中有2个课程,而其他属性有1个,则解决方案会显示所有属性。因为在数组中,他只插入

'course'         => (string)$item->courses->course[0]

So does my xml, it has also got attributes that other not have. how do I sort my xml and get everything displayed? Cheers.

我的xml也是如此,它也有其他没有的属性。如何排序我的xml并显示所有内容?干杯。

1 个解决方案

#1


0  

You need to use usort. This should work:

你需要使用usort。这应该工作:

<?php
$url = '001.XML';
$xml = simplexml_load_file($url);

$items = array();
foreach($xml->Images->ImageGalleryEntry as $item) {
    $items[] = $item;
};

// Custom sort on the names of the items:
usort ($items, function($a, $b) {
    return strcmp($a['Name'], $b['Name']);
});

foreach ($items as $item) {
    echo $item['FileName'] . "<br/>" . $item['Name'] . "<br/>" . $item['Description'] . "<br/><br/>";
}

#1


0  

You need to use usort. This should work:

你需要使用usort。这应该工作:

<?php
$url = '001.XML';
$xml = simplexml_load_file($url);

$items = array();
foreach($xml->Images->ImageGalleryEntry as $item) {
    $items[] = $item;
};

// Custom sort on the names of the items:
usort ($items, function($a, $b) {
    return strcmp($a['Name'], $b['Name']);
});

foreach ($items as $item) {
    echo $item['FileName'] . "<br/>" . $item['Name'] . "<br/>" . $item['Description'] . "<br/><br/>";
}