如何通过属性值PhP对xml子对象进行排序 [英] How to sort xml child via attribute value PhP

查看:51
本文介绍了如何通过属性值PhP对xml子对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过PHP的XML文件,我试图根据属性"word"在div中以升序列出特定的子级"word".

I have an XML file through PHP that I am trying to list a specific child "word" in ascending order in a div, according to the attribute "word".

我把sort($ word);没有成功

I put sort($word); without sucess

这是我的代码:

<?php
if(isset($_POST['submitSave'])) {
// Disable errors due to empty xml files
error_reporting(E_ALL & ~E_WARNING);

$domDoc = new DOMDocument('1.0');
$domDoc->preserveWhiteSpace = false;
$domDoc->formatOutput = true;
$xpath = new DOMXpath($domDoc);

// load xml file
try {
    $domDoc->load('./data/expression.xml');
} catch (\Throwable $th) {
    //throw $th;
}

if($domDoc->getElementsByTagName('expression')->length>0){
    // If we already have expression tag defined
    $expression = $domDoc->getElementsByTagName('expression')[0];
}else{
    // If we don't have any expression tag, i.e. file is empty
    $expression = $domDoc->createElement('expression');
}



  // Create child node for product and set id(attribute), word(child), 
  meaning(child)
$vocabulario = $domDoc->createElement('vocabulario');
$vocabulario->setAttribute('word', $_POST['word']);
$word = $domDoc->createElement('word', $_POST['word']);
$meaning = $domDoc->createElement('meaning', $_POST['meaning']);




$domDoc->appendChild($expression);
$expression->appendChild($vocabulario);
$vocabulario->appendChild($word);
$vocabulario->appendChild($meaning);



// convert returned node list into an array
$vocabularios = iterator_to_array(
// fetch all vocabulario elements
$xpath->evaluate('/expression/vocabulario')  
);
// sort the array
usort(
$vocabularios,
static function($a, $b) use ($xpath) {
    // compare the word child element
    return strcasecmp(
        $xpath->evaluate('string(word)', $a),
        $xpath->evaluate('string(word)', $b)
       );
      }
    );

// iterate the sorted array
foreach ($vocabularios as $vocabulario) {
// append node to the expression document element
// that moves nodes from their current position
$domDoc->documentElement->appendChild($vocabulario);
}




file_put_contents('./data/expression.xml', $domDoc->saveXML());

}
?>

输出

    <?xml version="1.0" encoding="UTF-8"?>
<expression>
  <vocabulario word="piece">
    <word>piece</word>
    <meaning>pedaço</meaning>
  </vocabulario>
  <vocabulario word="ball">
    <word>ball</word>
    <meaning>bola</meaning>
  </vocabulario>
</expression>

因此,如我在php页面中解析xml时所述,应按升序在件"之前列出球"一词.

So, the word "ball" should be listed before "piece", in ascending order as I said above when I parse the xml in a php page.

推荐答案

SimpleXML并不擅长操纵节点,因此使用DOM更容易.

SimpleXML is not good at manipulating nodes so this is a lot easier with DOM.

$document = new DOMDocument();
$document->preserveWhiteSpace = FALSE;
$document->loadXML($xmlString);
$xpath = new DOMXpath($document);

// convert returned node list into an array
$vocabularios = iterator_to_array(
    // fetch all vocabulario elements
    $xpath->evaluate('/expression/vocabulario')  
);
// sort the array
usort(
    $vocabularios,
    static function($a, $b) {
        // compare the word attribute
        return strcasecmp($a->getAttribute('word'), $b->getAttribute('word'));
    }
);

// iterate the sorted array
foreach ($vocabularios as $vocabulario) {
    // append node to the expression document element
    // that moves nodes from their current position
    $document->documentElement->appendChild($vocabulario);
}

$document->formatOutput = TRUE;
echo $document->saveXML();

要按子元素文本内容排序,只需更改比较功能即可.

To sort by child element text content you would just have to change the compare function.

usort(
    $vocabularios,
    static function($a, $b) use ($xpath) {
        // compare the word child element
        return strcasecmp(
            $xpath->evaluate('string(word)', $a),
            $xpath->evaluate('string(word)', $b)
        );
    }
);

这篇关于如何通过属性值PhP对xml子对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆