duan62819774 2016-02-04 22:54
浏览 38

使用php按xpath排序

Below is my Xml, i need to sort by age using xpath in php

<Guest>
<Ages>
<Age>22</Age>
<Age>6</Age>
<Age>5</Age>
<Age>2</Age>
<Age>12</Age>
</Ages>
</Guest>

i try below code, but not working

foreach ($xd->xpath('Guest/Ages[descendant::Age]') as $xd_age)
        {
            echo $xd_age->Age.',';
        }

I need like below

Ages : 2,5,6,12,22
  • 写回答

1条回答

  • douzou0073 2016-02-05 01:09
    关注

    Consider an XSLT solution. As information, XSLT is a special purpose, declarative language designed specifically to manipulate XML files (not just a stylesheet for HTML). Practically all the general purpose languages, Java, C#, Perl, Python, VB, carry XSLT 1.0 processors including PHP -even command line programs like PowerShell and Bash. Various dedicated processors also exist such as open source Saxon (which can run XSLT 2.0 scripts) and Apache's Xalan.

    PHP can both embed or call an external XSLT script (.xsl or .xslt) which by the way is a well-formed XML file. Below is an embedded solution:

    // Load the XML source
    $doc = new DOMDocument();
    $doc->load('Input.xml');
    
    $xslstr = '<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
                <xsl:output version="1.0" encoding="UTF-8" indent="yes" />
                <xsl:strip-space elements="*"/>
    
                  <!-- IDENTITY TRANSFORM -->
                  <xsl:template match="@*|node()">
                    <xsl:copy>
                      <xsl:apply-templates select="@*|node()"/>
                    </xsl:copy>
                  </xsl:template>  
    
                  <!-- SORT AGE CHILDREN IN EACH AGES NODE -->
                  <xsl:template match="Ages">
                    <xsl:copy>
                      <xsl:apply-templates select="Age">
                        <xsl:sort select="." order="ascending" data-type="number"/>
                      </xsl:apply-templates>
                    </xsl:copy>
                  </xsl:template>
    
                </xsl:transform>';
    
    $xsl = new DOMDocument;
    $xsl->loadXML($xslstr);
    
    // Configure the processor
    $proc = new XSLTProcessor;
    $proc->importStyleSheet($xsl); 
    
    // Transform XML source
    $newXml = $proc->transformToXML($doc);    
    echo $newXml;
    
    // Save output to file
    $xmlfile = 'Output.xml';
    file_put_contents($xmlfile, $newXml);
    

    Output

    <?xml version="1.0" encoding="UTF-8"?>
    <Guest>
      <Ages>
        <Age>2</Age>
        <Age>5</Age>
        <Age>6</Age>
        <Age>12</Age>
        <Age>22</Age>
      </Ages>
    </Guest>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料