Skip to content

Instantly share code, notes, and snippets.

@jesse1981
Created January 9, 2014 22:38
Show Gist options
  • Save jesse1981/8343421 to your computer and use it in GitHub Desktop.
Save jesse1981/8343421 to your computer and use it in GitHub Desktop.
Useful PHP functions to work with XMLs. libxml library is a required package
<?php
class xmlreader {
var $filename;
var $dataset;
public function __construct($filename) {
$this->filename = $filename;
$this->load($this->filename);
}
// private
private function load($filename) {
$handle = fopen($filename,'r');
$buffer = "";
if ($handle) {
$buffer = fread($handle,filesize($filename));
fclose($handle);
}
if ($buffer) { $this->dataset = simplexml_load_string($buffer); return true; }
else return false;
}
// public
public function getAttributes($node) {
$result = array();
if ($node) {
$atts = (array)$node->attributes();
if (count($atts)) {
foreach ($atts["@attributes"] as $a=>$b) {
$result[$a] = $b;
}
}
return $result;
}
else return false;
}
public function getChildren($node) {
if ($node) {
return $node->children();
}
else return false;
}
public function getXpath($path) {
$results = array();
if ($this->dataset) {
foreach ($this->xpath($path) as $result) $results[] = $result;
return $results;
}
else return -1;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment