PHP-Code:
class XmlWriter
{
var $xml;
var $indent;
var $stack = array();
function XmlWriter($indent = ' ')
{
$this->indent = $indent;
$this->xml = '<?xml version="1.0" encoding="utf-8"?>'."\n";
}
function _indent()
{
for ($i = 0; $i < count($this->stack); $i++) {
$this->xml .= $this->indent;
}
}
function push($element, $attributes = array())
{
$this->_indent();
$this->xml .= '<'.$element;
foreach ($attributes as $key => $value) {
$this->xml .= ' '.$key.'="'.htmlentities($value).'"';
}
$this->xml .= ">\n";
$this->stack[] = $element;
}
function element($element, $content, $attributes = array()) {
$this->_indent();
$this->xml .= '<'.$element;
foreach ($attributes as $key => $value) {
$this->xml .= ' '.$key.'="'.htmlentities($value).'"';
}
$this->xml .= '>'.htmlentities($content).'</'.$element.'>'."\n";
}
function emptyelement($element, $attributes = array())
{
$this->_indent();
$this->xml .= '<'.$element;
foreach ($attributes as $key => $value) {
$this->xml .= ' '.$key.'="'.htmlentities($value).'"';
}
$this->xml .= " />\n";
}
function pop()
{
$element = array_pop($this->stack);
$this->_indent();
$this->xml .= "</$element>\n";
}
function getXml()
{
return $this->xml;
}
}
PHP-Code:
require("xml.class.php");
$xml = new XmlWriter();
$array = array(
array('monkey', 'banana', 'Jim'),
array('hamster', 'apples', 'Kola'),
array('turtle', 'beans', 'Berty'),
);
$xml->push('zoo');
foreach ($array as $animal) {
$xml->push('animal', array('species' => $animal[0]));
$xml->element('name', $animal[2]);
$xml->element('food', $animal[1]);
$xml->pop();
}
$xml->pop();
echo $xml->getXml();
Es wird nur folgendes ausgegeben:
Jim banana Kola apples Berty beans
und nicht folgendes:
<?xml version="1.0" encoding="utf-8"?>
<zoo>
<animal species="monkey">
<name>Jim</name>
<food>banana</food>
</animal>
<animal species="hamster">
<name>Kola</name>
<food>apples</food>
</animal>
<animal species="turtle">
<name>Berty</name>
<food>beans</food>
</animal>
</zoo>
Was ist los ? Könnte jemand mal dieses Script ausprobieren ? Ist in meinem Browser etwas falsch eingestellt ?
Danke
Kommentar