Skip to content

Commit

Permalink
Support to namespaces in Xml::toArray.
Browse files Browse the repository at this point in the history
  • Loading branch information
jrbasso committed Jul 28, 2010
1 parent f4d5230 commit b862d68
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
18 changes: 11 additions & 7 deletions cake/libs/xml.php
Expand Up @@ -118,7 +118,8 @@ public static function toArray($simpleXML) {
throw new Exception(__('The input is not instance of SimpleXMLElement.'));
}
$result = array();
self::_toArray($simpleXML, $result);
$namespaces = array_merge(array('' => ''), $simpleXML->getNamespaces(true));
self::_toArray($simpleXML, $result, array_keys($namespaces));
return $result;
}

Expand All @@ -127,17 +128,20 @@ public static function toArray($simpleXML) {
*
* @param object $xml SimpleXMLElement object
* @param array $parentData Parent array with data
* @param array $namespaces List of namespaces in XML
* @return void
*/
protected static function _toArray($xml, &$parentData) {
protected static function _toArray($xml, &$parentData, $namespaces) {
$data = array();

foreach ($xml->attributes() as $key => $value) {
$data[$key] = (string)$value;
}
foreach ($namespaces as $namespace) {
foreach ($xml->attributes($namespace, true) as $key => $value) {
$data[$key] = (string)$value;
}

foreach ($xml->children() as $child) {
self::_toArray($child, $data);
foreach ($xml->children($namespace, true) as $child) {
self::_toArray($child, $data, $namespaces);
}
}

$asString = trim((string)$xml);
Expand Down
14 changes: 14 additions & 0 deletions cake/tests/cases/libs/xml.test.php
Expand Up @@ -323,6 +323,20 @@ function testToArray() {
)
);
$this->assertEqual(Xml::toArray($obj), $expected);

$xml = '<root xmlns:cake="http://www.cakephp.org/">';
$xml .= '<tag>defect</tag>';
$xml .= '<cake:bug>1</cake:bug>';
$xml .= '</root>';
$obj = Xml::build($xml);

$expected = array(
'root' => array(
'tag' => 'defect',
'bug' => 1
)
);
$this->assertEqual(Xml::toArray($obj), $expected);
}

}

0 comments on commit b862d68

Please sign in to comment.