標籤

2015年9月17日 星期四

XML which Contains Tags with Colon is Parsed by PHP

XML which Contains Tags with Colon is Parsed by PHP

  This webpage is to teach programmers about how to parse the xml webpage data. The contribution of this webpage is that you can do the further analysis after the parsing. Fig. 1 shows the example data we will parse. See demo result.

Fig. 1 shows the xml data


Put the code below into a php file:
____________________________________________________
Implementation                                                                             

// data array initialization
$total= array();
$data = array();

$feed= file_get_contents('http://opendata.dot.taipei.gov.tw/opendata/VD.xml');

$xmlobj = simplexml_load_string($feed);

if ($xmlobj===false)   die('Bad XML!');

// extract timestamp from xml object
$time=(string)$xmlobj->children('vd',true)->ExchangeTime[0];

//parse time to a standard timestamp 
list( $day, $hour) = split('T', $time);

//convert timestamp to epoch time
$epoch=strtotime($day." ".$hour);

//add data into 'data' array
$data['time']= $day." ".$hour;

//exhaust all the xml data
foreach ( $xmlobj->children('vd',true)->SectionDataSet->SectionData as $entry){

//add all field data into 'data' array
$data['id']= $entry->SectionId;
$data['name']= $entry->SectionName;
$data['spd']= $entry->AvgSpd;
$data['occ']= $entry->AvgOcc;
$data['vol']=  $entry->TotalVol;
$data['level']=  $entry->MOELevel;

// attach one 'data' array to 'total' array
array_push($total,$data);

// you can do further data manipulating at here 
}
//print 'total' array which is an array of array
echo  json_encode($total); 

Reference


  1. w3school
  2. SREEJITH PM

1 則留言: