items.xml sorter – by id/fromid

Simple PHP code to sort file items.xml by id/fromid attribute

<?php
$path_to_file = 'data/items/items.xml';
$xml = simplexml_load_string(file_get_contents($path_to_file));
$trees = $xml->xpath('/items/item');

function sort_trees($t1, $t2)
{
    $a = isset($t1['id']) ? $t1['id'] : $t1['fromid'];
    $b = isset($t2['id']) ? $t2['id'] : $t2['fromid'];
    return $a - $b;
}

usort($trees, 'sort_trees');

foreach ($trees as $tree) {
    echo '<item ';
    foreach ($tree->attributes() as $k => $v) {
        echo $k . '="' . $v . '" ';
    }
    if (count($tree->attribute) > 0) {
        echo '>' . PHP_EOL;
        foreach ($tree->attribute as $k => $v) {
            echo '<attribute key="' . $v->attributes()['key'] . '" value="' . htmlspecialchars($v->attributes()['value'], ENT_XML1 | ENT_QUOTES, 'UTF-8') . '" />' . PHP_EOL;
        }
        echo '</item>' . PHP_EOL;
    } else {
        echo '/>' . PHP_EOL;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *