使用PHP

时间:2016-07-09 17:19:01

标签: php xml filter

我试图返回最后排序的固定数量的XML节点,以便我可以显示“最近添加的”过滤器。我没有存储日期。如何使用PHP过滤最后10个节点?

XML:

<?xml version="1.0" encoding="utf-8"?>
<trackList>
  <track>
    <title>Lost in the Star</title>
    <creator>Toshiki Hayashi</creator>
    <cover>images/thinlines.jpg</cover>
    <location>mp3/toshiki hayashi - lost in the star.mp3</location>
    <genre>hip-hop</genre>
    <playlist>2</playlist>
  </track>
  <track>
    <title>Black Orpheusr</title>
    <creator>Ouska</creator>
    <cover>images/ouska.jpg</cover>
    <location>mp3/ouska - Black Orpheus.mp3</location>
    <genre>rock</genre>
    <playlist>2</playlist>
  </track>
  <track>
    <title>Soul Below</title>
    <creator>Ljones</creator>
    <cover>images/Ljones.jpg</cover>
    <location>mp3/Ljones - Soul Below.mp3</location>
    <genre>hip-hop</genre>
    <playlist>2</playlist>
  </track>
</trackList>

PHP:

<?php
$xml = new SimpleXMLElement('playlist100.xml', NULL, TRUE);

foreach($xml->xpath('//track[playlist="1"]') as $child)
    {
    echo '<div class="song"><a href="' . $child->location . '">';
    echo '<img src="' . $child->cover . '" alt="cover" />';
    echo '<span class="artist">' . $child->creator . '</span>';
    echo '<span class="songTitle">' . $child->title . '</span></a></div>';
    }

?>

1 个答案:

答案 0 :(得分:0)

考虑一种XSLT解决方案,您可以使用count()函数将原始文件转换为仅选择最后10个节点。由于XSLT是格式良好的XML文件,因此您可以像任何其他XML文件一样阅读它,使用它来转换原始文件,并使用SimpleXML处理输出。

XSLT (外部保存为.xsl或以PHP格式嵌入字符串)

<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="*" />

  <xsl:template match="trackList">
    <xsl:copy>
      <xsl:variable name="count" select="count(track) - 9"/>
      <xsl:apply-templates select="track[position() &gt;= $count]"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="track">
   <xsl:copy-of select="."/>
  </xsl:template>   

</xsl:transform>

PHP 脚本

// LOAD XML AND XSL FILES
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->load('playlist100.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($dom);

// PROCESS NEW XML STRING
$xml = new SimpleXMLElement($newXml);

foreach($xpath = $xml->xpath('//track') as $child)
    {
    echo '<div class="song"><a href="' . $child->location . '">';
    echo '<img src="' . $child->cover . '" alt="cover" />';
    echo '<span class="artist">' . $child->creator . '</span>';
    echo '<span class="songTitle">' . $child->title . '</span></a></div>';
    }