簡體   English   中英

用php讀取xml文件目錄

[英]reading a directory of xml files with php

我有這段代碼可以找到目錄中的每個xml文件,然后獲取日期。 但是我希望它代替在目錄中每個xml文件中的每一行。 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>

作為一種簡單的解決方案,如果您想將事件作為循環的一部分回顯,則可以執行以下操作:

$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部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM