2013-01-31 118 views
0

我有這個代碼可以找到目錄中的每個xml文件,然後獲取日期。但是我希望它在目錄中的每個xml文件中回顯每行。 的XML文件看起來像這樣用php讀取xml文件的目錄

<event> 
<day>11</day> 
<month>01</month> 
<year>2013</year> 
<link>link</link> 
<title>Title</title> 
<description></description> 
</event> 

和我的PHP代碼

$events = array(); 

// open each xml file in this directory 
foreach(glob("*.xml") as $filename) { 
    // get the contents of the the current file 
    $xml_file = file_get_contents($filename, FILE_TEXT); 

    // create a simplexml object from the contents of the current file 
    $xml = simplexml_load_string($xml_file); 

    // create a day, link, description, etc. 
    $eventDay = (int)$xml->day; 
    $eventMonth = (int)$xml->month; 
    $eventYear = (int)$xml->year; 
    $eventLink = (string)$xml->link; 
    $eventDesc = (string)$xml->description; 

    if($eventMonth == $month && $eventYear == $year)   
     $events[$eventDay] = array($eventLink,'linked-day'); 
} 
return $events; 

}

因此,例如,每個文件發現它會打印出像

<div class="event"><p>Date: month/day/year</p><p>Title: the xml title</p><p>description: the xml description</p></div> 

回答

0

東西作爲一個簡單的解決方案,如果你想回顯事件作爲循環的一部分喲ü可以做到這一點:

$events = array(); 

// open each xml file in this directory 
foreach(glob("*.xml") as $filename) { 
    // get the contents of the the current file 
    $xml_file = file_get_contents($filename, FILE_TEXT); 

    // create a simplexml object from the contents of the current file 
    $xml = simplexml_load_string($xml_file); 

    // create a day, link, description, etc. 
    $eventDay = (int)$xml->day; 
    $eventMonth = (int)$xml->month; 
    $eventYear = (int)$xml->year; 
    $eventLink = (string)$xml->link; 
    $eventDesc = (string)$xml->description; 
    $eventTitle = (string)$xml->title;   

    if($eventMonth == $month && $eventYear == $year)   
     $events[$eventDay] = array($eventLink,'linked-day'); 

    echo "<div class=\"event\"> 
      <p>Date: {$eventMonth}/{$eventDay}/{$eventYear}</p> 
      <p>Title: {$eventTitle}</p> 
      <p>description: {$eventDesc}</p> 
      </div>"; 

} 
return $events; 

唯一的補充是$eventTitleecho部分。

+0

非常感謝約翰。哇,這很容易(我覺得有點愚蠢,現在哈哈)所以它的工作原理,但現在我無法得到它按日期排序的XML文件中排序日期文件的創建日期。我將如何根據xml文件本身的日期進行排序? –

+0

@KarenBemusOsh很高興幫助!如果您的問題得到解答,您可以[標記爲正確](http://meta.stackexchange.com/a/5235/188816)。要按日期排序,您必須首先將所有事件收集到一個數組中(類似於您所擁有的$ events),然後您可以對它們進行排序和顯示。 –