1

我有一个包含节目和季节的 xml 文件。

我想做的是读出一个节目的季节。但问题是每个季节都在同一个节目下多次出现。

我只希望每个季节编号打印一次,例如:

Season 1
Season 2

但我现在得到的是:

Season 1
Season 2
Season 2
Season 1
Season 1

我的 xml 看起来像

<?xml version="1.0"?>
<episodeview>
<episodeview>
    <idShow>1</idShow>
    <idSeason>1</idSeason>
</episodeview>
<episodeview>
    <idShow>1</idShow>
    <idSeason>2</idSeason>
</episodeview>
<episodeview>
    <idShow>1</idShow>
    <idSeason>2</idSeason>
</episodeview>
<episodeview>
    <idShow>1</idShow>
    <idSeason>1</idSeason>
</episodeview>
<episodeview>
    <idShow>1</idShow>
    <idSeason>1</idSeason>
</episodeview>
</episodeview>

还有我的 php 文件:

<?php
$idShow = "1";
$source = "show.xml";

$xmlstr = file_get_contents($source);
$xmlcont = new SimpleXMLElement($xmlstr);
foreach($xmlcont as $url) {
    if ($url->idShow == $idShow) {
        $test = $url->idSeason;
        echo "Season ";
        echo $test;
        echo "<br>";
     }      
}

?>

4

3 回答 3

3

试试这个,简短而甜蜜:

 $xml=simplexml_load_file($source); // (1)

 foreach ($xml->xpath("//idSeason") As $season) { // (2)

      $s[(int)$season]=$season; // (3)
 }

 foreach ($s As $a) echo "Season $a<br />"; // (4)
  1. 从文件中获取simplexml-Element

  2. 仅使用并遍历它们选择<idSeason>-nodesxpath

  3. 创建一个$s以 season-id 作为索引和值的新数组 --> 数组索引必须是唯一的,因此重复的 id 不会扩大数组,而是“覆盖”已经存在的索引。

  4. 迭代$s以回显它

我知道人们只能通过 选择唯一值xpath,但我不是那么熟练;-) 并且 simplexml 不支持更容易的 xpath 2.0。

于 2013-02-26T22:28:44.057 回答
1

我会这样做:

<?php
  $idShow = "1";
  $source = "show.xml";

  $xmlstr  = file_get_contents($source);
  $xmlcont = new SimpleXMLElement($xmlstr);
  $seasons = array();
  foreach($xml_cont as $url){ $seasons[] = $url->idSeason; }

  $seasons = array_uniq($seasons);

  foreach($seasons as $season){ echo "Season $season <br />"; } 
?>

诚然,与您可能尝试的其他一些解决方案相比,我的示例涉及更多的循环,但我认为它相当有效,也许同样重要的是,可读性强。

于 2013-02-26T22:38:39.450 回答
1

尝试:

<?php
$idShow = "1";
$source = "show.xml";
$have = array();

$xmlstr = file_get_contents($source);
$xmlcont = new SimpleXMLElement($xmlstr);
foreach($xmlcont as $url) {
    if ($url->idShow == $idShow) {
        $test = $url->idSeason;
         if( ! in_array( $test, $have) ){ //Check if the season already is displayed
           echo "Season ";
           echo $test;
           echo "<br>";
           $have[] = $test; //Store the season in the array
          }
     }      
}

这样您就可以将显示的所有内容存储在数组中,并且在输出测试之前,它会检查它是否已经显示。

于 2013-02-26T22:21:52.910 回答