Created
April 28, 2014 14:48
-
-
Save glensc/11374378 to your computer and use it in GitHub Desktop.
Overly simple XML parser.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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