简体   繁体   中英

reading a directory of xml files with php

I have this code that finds every xml file in a directory and then grabs the dates. But I want it instead to echo each line in each xml file in the directory. the xml files look like this

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

and my php code

$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;

}

so for example for each file found it would print out something like

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

As a simplistic solution, if you want to echo the events out as part of the loop you can do this:

$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;

The only additions are the $eventTitle and echo sections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM