經典例子。作爲信息,XSLT(其腳本是格式良好的XML文檔)是用於轉換XML文件的專用語言。像大多數通用語言一樣,PHP使用XSLT 1.0處理器。
下面的XSLT腳本在<AppID>
和<Date>
的連接上運行<xsl:key>
,然後計算不同的組值。事實上,XSLT可以輸出字符串行而不需要一個for
循環!
XML輸入(可重複的例子)
<Logs>
<Log>
<AppID>12345</AppID>
<Module>Falcon</Module>
<Info>Avengers Assemble</Info>
<Date>2016-06-01</Date>
</Log>
<Log>
<AppID>12345</AppID>
<Module>Captain America</Module>
<Info>Avengers Assemble</Info>
<Date>2016-06-01</Date>
</Log>
<Log>
<AppID>12557</AppID>
<Module>Black Widow</Module>
<Info>Avengers Assemble</Info>
<Date>2016-06-01</Date>
</Log>
<Log>
<AppID>12345</AppID>
<Module>Iron Man</Module>
<Info>Avengers Assemble</Info>
<Date>2016-06-02</Date>
</Log>
<Log>
<AppID>12557</AppID>
<Module>Hulk</Module>
<Info>Avengers Assemble</Info>
<Date>2016-06-02</Date>
</Log>
<Log>
<AppID>12557</AppID>
<Module>Blackhawk</Module>
<Info>Avengers Assemble</Info>
<Date>2016-06-01</Date>
</Log>
<Log>
<AppID>12345</AppID>
<Module>Thor</Module>
<Info>Avengers Assemble</Info>
<Date>2016-06-01</Date>
</Log>
</Logs>
XSLT腳本(保存爲文件的.xsl下面將要加載)
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output version="1.0" encoding="UTF-8" indent="yes" omit-xml-declaration="yes" />
<xsl:strip-space elements="*"/>
<xsl:key name="appkey" match="Log" use="concat(AppID, Date)" />
<xsl:template match="Logs">
<xsl:apply-templates select="Log[generate-id() =
generate-id(key('appkey',concat(AppID, Date))[1])]">
<xsl:sort select="concat(Date, AppID)"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="Log[generate-id() =
generate-id(key('appkey',concat(AppID, Date))[1])]">
<xsl:value-of select="concat(Date, ': ', AppID, ' ',
count(. | key('appkey', concat(AppID, Date))), ' times')"/>
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:transform>
PHP腳本
// LOAD XML AND XSL FILES
$xmlfile = new DOMDocument('1.0', 'UTF-8');
$xmlfile->load('Input.xml');
$xslfile = new DOMDocument('1.0', 'UTF-8');
$xslfile->load('XSLTScript.xsl');
// TRANSFORM XML with XSLT
$proc = new XSLTProcessor;
$proc->importStyleSheet($xslfile);
$newXml = $proc->transformToXML($xmlfile);
// ECHO OUTPUT STRING
echo $newXml;
# 2016-06-01: 12345 3 times
# 2016-06-01: 12557 2 times
# 2016-06-02: 12345 1 times
# 2016-06-02: 12557 1 times
確切地說,你嘗試了什麼? foreach是很好的,但這是問題中最簡單的部分。 –
我創建了一個包含所有發生日期的數組(使用!in_array) - 但現在我不知道每個日期的每個AppID的計數並將其引用到日期。 –