用php读取xml文件的目录

时间:2013-01-31 17:22:24

标签: php xml directory

我有这个代码可以找到目录中的每个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>

1 个答案:

答案 0 :(得分: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部分。