- substr: documentation ( source)
- var_dump: documentation ( source)
<?php
class XmlArrayAccessIterator implements ArrayAccess, IteratorAggregate
{
const ATTRIBUTE_PREFIX = '@';
private $xml;
public function __construct(SimpleXmlIterator $xml)
{
$this->xml = $xml;
}
private function getElement($offset)
{
$isAttribute = false;
if (substr($offset, 0, 1) == self::ATTRIBUTE_PREFIX) {
$offset = substr($offset, 1);
$isAttribute = false;
}
var_dump($this->xml->$offset->asXML());
if (false !== $this->xml->$offset->asXML() && !$isAttribute) {
$xml = $this->xml->$offset;
}
else {
$xml = $this->xml[$offset];
}
}
public function offsetExists($offset)
{
return !is_null($this->getElement($offset));
}
public function offsetGet($offset)
{
if ($this->xml->getName() == $offset) {
return $this;
}
$xml = $this->getElement($offset);
if (is_null($xml)) {
throw new RuntimeException('unknown node or attribute "' . $offset . '"');
}
return new self($xml);
}
public function offsetSet($offset, $value)
{
throw new RuntimeException('This is readonly. writing to "' . (string) $offset . '" with value "' . (string) $value . '" not possible');
}
public function offsetUnset($offset)
{
throw new RuntimeException('This is readonly. Unsetting "' . (string) $offset . '" not possible');
}
public function getIterator()
{
return $this->xml;
}
public function __toString()
{
return (string) $this->xml;
}
}
$xml = '<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading foo="bar">Reminder</heading>
<body>Don\'t forget me this weekend!</body>
<recursive>
<val>2</val>
<val>4</val>
</recursive>
</note>';
$simple = new SimpleXmlIterator($xml);
$xml = new XmlArrayAccessIterator($simple);
echo $xml['note']['to'];
echo $xml['note']['recursive']['val'][1];
echo $xml['note']['heading']['@foo'];