Skip to content

Instantly share code, notes, and snippets.

@glensc
Created April 28, 2014 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glensc/11374378 to your computer and use it in GitHub Desktop.
Save glensc/11374378 to your computer and use it in GitHub Desktop.
Overly simple XML parser.
<?php
/**
* Overly simple XML parser.
*
* Does not parse CDATA nor nested tags well
*
* @author Elan Ruusamäe <glen@delfi.ee>
*/
class XmlParserException extends RuntimeException {
}
class XmlParser {
public function __construct($file) {
$state = libxml_use_internal_errors(true);
$el = simplexml_load_file($file);
libxml_use_internal_errors($state);
if ($el === false) {
$errors = $this->getXmlErrors();
throw new XmlParserException("Can't load $file: $errors");
}
// this will flatten
$this->data = json_decode(json_encode($el), true);
}
private function getXmlErrors($separator = "\n") {
$errors = array();
foreach (libxml_get_errors() as $error) {
$errors[] = $error;
}
libxml_clear_errors();
return join($separator, $errors);
}
public function getElements() {
return $this->data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment