xml2array.class.php
Código PHP:
<?php
class xml2array
{
const XML2ARRAY_ATTRIBUTES = '__atributtes';
const XML2ARRAY_NODEVALUE = '__nodevalue';
public $error;
private $array = array();
public function __construct($dom, $charset = 'utf-8', $version = '1.0')
{
$d = $this->loadXML($dom, $version, $charset);
if(!$this->error)
$this->array = $this->dom2array($d);
unset($dom, $charset, $version, $d);
}
public function getArray()
{
if(!$this->array)
$this->error = 'E_ARRAY';
else
return $this->array;
}
private function loadXML($dom, $version, $charset)
{
$a = new DOMDocument($version, $charset);
$a->preserveWhiteSpace = false;
if(@$a->load($dom))
return $a;
elseif(@$a->loadXML($dom))
return $a;
$this->error = 'E_XML';
}
private function dom2array($dom, $parent = array())
{
if(is_object($dom->childNodes->item(0)) && $dom->nodeType!==8 && ($dom->childNodes->item(0)->nodeType===3 || $dom->childNodes->item(0)->nodeType===4))
$a = $dom->childNodes->item(0)->nodeValue;
else
{
$i = 0;
$beforeNode = '';
$a = array();
foreach($dom->childNodes as $b)
{
$array = array();
if($b->nodeType!==8)
{
if($beforeNode!=$b->nodeName)
{
$beforeNode = $b->nodeName;
$i = 0;
}
if($b->hasAttributes())
$a[$b->nodeName][$i][self::XML2ARRAY_ATTRIBUTES] = self::getAttributes($b);
if($parent)
$c = self::dom2array($b, $array[$parent][$b->nodeName]);
else
$c = self::dom2array($b, $array[$b->nodeName] = array());
$a[$b->nodeName][$i][self::XML2ARRAY_NODEVALUE] = $c;
}
$i++;
}
unset($dom, $parent, $b, $i, $beforeNode, $c);
return $a;
}
unset($dom, $parent);
return $a;
}
private function getAttributes($node)
{
$attr = array();
foreach($node->attributes as $a)
$attr[$a->name] = $a->value;
return $attr;
}
}
Código PHP:
<?php
error_reporting(E_ALL);
include('xml2array.class.php');
$a = new xml2array('example.xml');
if(!$a->error)
{
$b = $a->getArray();
if(!$a->error)
{
echo "<pre>";
print_r($b);
echo "</pre>";
}
else
echo $a->error;
}
else
echo $a->error;
?>
Código xml:
Ver original
<?xml version="1.0" encoding="utf-8"?> <a id="forosdelweb"> <b id="usuario" id2="fecha"> zital </b> <b> hola </b> </a>
Resultado:
Código:
Como entrada se puede poner el nombre del fichero XML o incluso un XML dentro de una variable :) Array ( [a] => Array ( [0] => Array ( [__attributes] => Array ( [id] => forosdelweb ) [__value] => Array ( [b] => Array ( [0] => Array ( [__attributes] => Array ( [id] => usuario [id2] => fecha ) [__value] => zital ) [1] => Array ( [__value] => hola ) ) ) ) ) )