note 111219 added to book.dom
| From: | qeremy | Date: | Mon, 28 Jan 2013 01:53:04 +0000 |
| Subject: | note 111219 added to book.dom | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-193406@lists.php.net to get a copy of this message | ||
Correction for "dom_to_array" function below;
<?php
function xml_to_array($root) {
$result = array();
if ($root->hasAttributes()) {
$attrs = $root->attributes;
foreach ($attrs as $attr) {
$result['@attributes'][$attr->name] = $attr->value;
}
}
if ($root->hasChildNodes()) {
$children = $root->childNodes;
if ($children->length == 1) {
$child = $children->item(0);
if ($child->nodeType == XML_TEXT_NODE) {
$result['_value'] = $child->nodeValue;
return count($result) == 1
? $result['_value']
: $result;
}
}
$groups = array();
foreach ($children as $child) {
if (!isset($result[$child->nodeName])) {
$result[$child->nodeName] = xml_to_array($child);
} else {
if (!isset($groups[$child->nodeName])) {
$result[$child->nodeName] = array($result[$child->nodeName]);
$groups[$child->nodeName] = 1;
}
$result[$child->nodeName][] = xml_to_array($child);
}
}
}
return $result;
}
?>
Some test;
<?php
$s = '<?xml version="1.0" encoding="UTF-8"
standalone="no"?>
<response>
<resData foo="1">
<contact:infData xmlns:contact="http://example.com/contact-1.0"
bar="1">
<contact:status s="value1"/>
<contact:status s="value2"/>
<contact:status s="value3"/>
<contact:status s="value4"/>
</contact:infData>
</resData>
</response>';
$xml = new DOMDocument();
$xml->loadXML($s);
$xmlArray = xml_to_array($xml);
print_r($xmlArray);
//
print_r($xmlArray['response']['resData']['contact:infData']['contact:status'][0]['@attributes']['s']);
// foreach
($xmlArray['response']['resData']['contact:infData']['contact:status']
as $status) {
// echo $status['@attributes']['s'] ."\n";
// }
?>
----
Server IP: 69.147.83.199
Probable Submitter: 88.253.127.241
----
Manual Page -- http://php.net/manual/en/book.dom.php
Edit -- https://master.php.net/note/edit/111219
Del: integrated -- https://master.php.net/note/delete/111219/integrated
Del: useless -- https://master.php.net/note/delete/111219/useless
Del: bad code -- https://master.php.net/note/delete/111219/bad+code
Del: spam -- https://master.php.net/note/delete/111219/spam
Del: non-english -- https://master.php.net/note/delete/111219/non-english
Del: in docs -- https://master.php.net/note/delete/111219/in+docs
Del: other reasons-- https://master.php.net/note/delete/111219
Reject -- https://master.php.net/note/reject/111219
Search -- https://master.php.net/manage/user-notes.php