Skip to content

Instantly share code, notes, and snippets.

@yang-wei
Created May 15, 2014 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yang-wei/b414db57df3f4cd7d94c to your computer and use it in GitHub Desktop.
Save yang-wei/b414db57df3f4cd7d94c to your computer and use it in GitHub Desktop.
<?php
header('Content-Type: application/json');
//$xmlfile = 'xml/EIT_00002_20140507.xml';
function xml2json($file) {
if (file_exists($file)) {
$xml = simplexml_load_file($file);
$date = $xml->EventDate;
foreach ($xml->Event as $data) {
$filtered_xml = [];
$startime = (string)$data->EventStartTime;
$endtime = (string)$data->EventEndTime;
$filtered_xml['id'] = (string)$data->event_id;
$filtered_xml['name'] = (string)$data->EventDetailInfo->eventName;
$filtered_xml['description'] = (string)$data->Extended_DetailInfo->message;
$filtered_xml['startime'] = getEpoch($date.$startime);
$filtered_xml['endtime'] = getEpoch($date.$endtime);
$filtered_xml['duration'] = $filtered_xml['endtime'] - $filtered_xml['startime'];
$json = json_encode(($filtered_xml), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE). ",";
$output .= $json;
}
return $output;
} else {
exit('Failed to open '.$file);
}
}
function getEpoch($datestring) {
$timeEpoch = DateTime::createFromFormat('YmdHis', $datestring)->getTimestamp();
return $timeEpoch;
}
//loop through directory for each xml file
$xmlfiles = glob('xml/*.{xml}', GLOB_BRACE);
foreach ($xmlfiles as $xmlfile) {
//set the output file name to .json
$filename = basename($xmlfile, ".xml").".json";
$result = xml2json($xmlfile);
//create new file
$handle = fopen($_SERVER['DOCUMENT_ROOT'] ."/lim/xmltojson/json/". $filename, "w") or die ('Cannot open file: ' .$filename);
//write json data into new file
if( fwrite($handle, $result) === FALSE) {
echo "Cannot write to file.";
exit;
}
echo "Success wrote date to file:" .$filename ."\n";
fclose($handle);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment