Skip to content

Instantly share code, notes, and snippets.

@stovak
Created July 17, 2015 16:46
Show Gist options
  • Save stovak/0c193cd5a285c1caea43 to your computer and use it in GitHub Desktop.
Save stovak/0c193cd5a285c1caea43 to your computer and use it in GitHub Desktop.
Parse Apple HealthKit export.xml
#!/usr/bin/env php
<?php
class RecordFile {
var $parser;
var $records = [];
function __construct($filename = null) {
if (file_exists($filename) && $filename !== null){
$this->parser = simplexml_load_file($filename);
foreach ($this->parser->children() as $name => $child) {
$record = new Record($child);
if (!empty($record->type)) {
$this->records[] = $record;
}
}
} else {
throw new Exception("File does not exist");
}
}
function __toString() {
$toReturn = [];
foreach($this->records as $record) {
$toReturn[$record->type] .= $record->type." ".$record->__toString() . PHP_EOL ;
}
return join(PHP_EOL, $toReturn);
}
}
class Record {
var $element;
var $type;
var $date;
var $value;
function __construct(SimpleXMLElement $child) {
$type = @$child->attributes()['type'];
if (empty($type)){
return null;
} else {
$this->type = str_replace("HKQuantityTypeIdentifier", "", $type);;
$this->element = $child;
$this->parseElement();
}
}
function parseElement() {
$this->date = $this->iOSStringToDateTime(@$this->element->attributes()['startDate']);
$this->value = @$this->element->attributes()['average'];
if (empty($this->value)){
$this->value = @$this->element->attributes()['value'];
}
}
function iOSStringToDateTime($incoming) {
$year = substr($incoming, 0, 4);
$month = substr($incoming, 4, 2);
$day = substr($incoming, 6, 2);
$hour = substr($incoming, 8, 2);
$minute = substr($incoming, 10, 2);
return new DateTime($year."-".$month."-".$day." ".$hour.":".$minute.":"."00", new DateTimeZone("America/Los_Angeles"));
}
function __toString() {
return (string) $this->date->format("l Y-m-d h:iA") . " " . $this->value;
}
}
$args = $argv;
$scriptname = array_shift($args);
if (count($args) <= 0) {
throw new Exception("This script requires a filename to parse. e.g. > ".$scriptname." ./file.xml");
}
$recordFile = new RecordFile(array_shift($args));
print($recordFile->__toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment