Main function: Use DOM class to read XML file in PHP
Design Knowledge Points:
1, XML node loop read
2, using Iconv () function to achieve code conversion to prevent Chinese garbled
Holiday.xml files are as follows
Copy Code code as follows:
<?xml version= "1.0" encoding= "UTF-8"?>
<daysOff-overTime>
<year>
<yearName>2012</yearName>
<daysOff>
<from>2012-1-1</from>
<to>2012-1-3</to>
</daysOff>
<overTime>
<day>2011-12-31</day>
</overTime>
<daysOff>
<from>2012-1-22</from>
<to>2012-1-28</to>
</daysOff>
<overTime>
<day>2012-1-21</day>
<day>2012-1-29</day>
</overTime>
<daysOff>
<from>2012-4-2</from>
<to>2012-4-4</to>
</daysOff>
<overTime>
<day>2012-3-31</day>
<day>2012-4-1</day>
</overTime>
<daysOff>
<from>2012-4-29</from>
<to>2012-5-1</to>
</daysOff>
<overTime>
<day>2012-4-28</day>
</overTime>
<daysOff>
<from>2012-6-22</from>
<to>2012-6-24</to>
</daysOff>
<overTime/>
<daysOff>
<from>2012-9-30</from>
<to>2012-10-7</to>
</daysOff>
<overTime>
<day>2012-9-26</day>
</overTime>
</year>
</daysOff-overTime>
The PHP code is as follows:
Copy Code code as follows:
<?php
reading XML files
$xmlDoc = new DOMDocument ();
$xmlDoc->load (' http://127.0.0.1/holiday.xml ');
Get all the years in the XML file
$years = $xmlDoc->getelementsbytagname ("year");
Processing for each year
foreach ($years as $year) {
Get a specific year value
$yearNames = $year->getelementsbytagname ("Yearname");
$yearName = $yearNames->item (0)->nodevalue;
echo $yearName. ' Year '. ' </br> ';
Get all the holidays in the year
$holidays = $year->getelementsbytagname ("Holiday");
Deal with each holiday
foreach ($holidays as $holiday) {
Get Holiday Name
$holidayNames = $holiday->getelementsbytagname ("Holidayname");
$holidayName = $holidayNames->item (0)->nodevalue;
echo iconv (' Utf-8 ', ' gb2312 ', $holidayName). ' </br> ';
Get a specific holiday date
$daysOffs = $holiday->getelementsbytagname ("Daysoff");
$DAYSOFF = $daysOffs->item (0);
$froms = $daysOff->getelementsbytagname ("from");
$from = $froms->item (0)->nodevalue;
$tos = $daysOff->getelementsbytagname ("to");
$to = $tos->item (0)->nodevalue;
Echo ' Vacation is: '. $from. ' to '. $to. ' </br> ';
Get the lieu date for the holiday
$overTimes = $holiday->getelementsbytagname ("overtime");
$overTime = $overTimes->item (0);
$days = $overTime->getelementsbytagname ("Day");
By judging, there are lieu dates are displayed, no is not displayed
if ($days->length!=0) {
Echo ' Lieu day as: ';
foreach ($days as $day) {
echo $day->nodevalue. ' ';
}
Echo ' </br> ';
}
Echo ' </br> ';
}
}
?>
Output display: