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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置