在php中按元素排序XML数据


Sort XML data by element in php

我对编码很不熟悉,我的大学有一些练习练习,第一个是采用XML文档并使用php返回数据,我已经设法做到了,但是下一步是通过一个名为'note_id'的新子元素或通过添加'id'属性到注释元素来排序该数据,然后按降序显示数据。我去添加一个新的子元素note_id,我已经插入note_id编号6在其他元素的中间,看看它是否会排序。

我通过在互联网上查找信息尝试了许多事情,但是我觉得我只是在兜圈子,因为我是新的,似乎没有什么工作(显然,因为我不知道我在做什么-但必须从某个地方开始)。

我没有张贴这个问题只是为了得到一个答案,我也需要了解如何以及为什么这个方法工作,如果有人回答一个答案。

我的XML数据如下所示,存储在一个名为'note.xml'的文件中。

    <?xml version="1.0" encoding="UTF-8"?>
<notes>
<note>
<note_id>1</note_id>
<to>tove1</to>
<from>Jani1</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<note_id>2</note_id>
<to>tove2</to>
<from>Jani2</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<note_id>3</note_id>
<to>tove3</to>
<from>Jani3</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<note_id>6</note_id>
<to>tove6</to>
<from>Jani6</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<note_id>4</note_id>
<to>tove4</to>
<from>Jani4</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<note_id>5</note_id>
<to>tove5</to>
<from>Jani5</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
</notes>

下面是我当前的PHP代码,它带来了XML。

?php
// Loads the xml file.
$xml= simplexml_load_file("note.xml");
// Returns the top level xml element - notes.
echo $xml->getName() . "<br />";

// Returns each note element.
foreach($xml->note as $note){
     echo $note->getName() . ": " . $note . "<br />";
// Returns each child element of note element.
    foreach($note->children() as $child){
        echo $child->getName() . ": " . $child . "<br />";
    }
    echo "<br />";
}

echo "<br />";

?>

下面是一个示例:

  • 加载note.xml文件。在本例中,我使用了一个自定义的Note类,它将通过将文件传递给构造函数来加载文件。
  • 您要按'note_id'对xml进行排序。为此,您可以将xml转换为数组的数组,其中数组实际上是注释。
  • 现在你已经有了一个数组的数组,你可以使用php原生的ussort函数对这些数组进行排序:

  • 然后,您可以根据数组的排序数组生成新的xml

的例子:

<?php
class Note
{
    /**
     * @var array
     */
    private $notes = [];
    /**
     * @param $fileName
     */
    public function __construct($fileName)
    {
        $xml = simplexml_load_file($fileName);
        $this->simpleXMLElementToArray($xml);
    }
    /**
     * Convert the SimpleXMLElement to array format.
     *
     * @param SimpleXMLElement $xml
     */
    protected function simpleXMLElementToArray(SimpleXMLElement $xml)
    {
        // For each note, create an associative array and add it to the $notes array
        foreach ($xml->note as $note) {
            $this->notes[] = json_decode(json_encode($note), true);
        }
    }
    /**
     * Sort the internal $notes array using usort.
     *
     * http://php.net/manual/en/function.usort.php
     */
    public function sortByNoteIdDescending()
    {
        usort($this->notes, array('Note', 'sortNotesArrayByNoteIdDescending'));
    }
    /**
     * Custom function to sort by note_id.
     *
     * @param array $note1
     * @param array $note2
     * @return int
     */
    protected function sortNotesArrayByNoteIdDescending(array $note1, array $note2)
    {
        if ($note1['note_id'] == $note2['note_id']) {
            return 0;
        } else if ($note1['note_id'] < $note2['note_id']) {
            return 1;
        } else {
            return -1;
        }
    }
    /**
     * Generate xml from the internal $notes array.
     */
    public function toXml()
    {
        $xml = new SimpleXMLElement('<notes/>');
        foreach ($this->notes as $note ) {
            $noteElement = $xml->addChild('note');
            $noteElement->addChild("note_id", $note["note_id"]);
            $noteElement->addChild("to", $note["to"]);
            $noteElement->addChild("from", $note["from"]);
            $noteElement->addChild("body", $note["body"]);
        }
        // To generate a nice output format
        $dom = dom_import_simplexml($xml)->ownerDocument;
        $dom->formatOutput = true;
        return $dom->saveXML();
    }
}
$note = new Note('note.xml');
$note->sortByNoteIdDescending();
echo $note->toXml();