Reputation: 177
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
Upvotes: 0
Views: 206
Reputation: 107587
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>
Upvotes: 1