note 108112 added to class.simplexmlelement
| From: | demian dot katz at villanova dot edu | Date: | Thu, 29 Mar 2012 17:50:07 +0000 |
| Subject: | note 108112 added to class.simplexmlelement | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-186902@lists.php.net to get a copy of this message | ||
Here is a more namespace-aware version of the earlier function for attaching one SimpleXMLElement to
another. I'm sure it could still be further improved (right now it generates some redundant
xmlns definitions), but it seems to be working well enough for my purposes so far.
function SimpleXMLElement_append($parent, $child)
{
// get all namespaces for document
$namespaces = $child->getNamespaces(true);
// check if there is a default namespace for the current node
$currentNs = $child->getNamespaces();
$defaultNs = count($currentNs) > 0 ? current($currentNs) : null;
$prefix = (count($currentNs) > 0) ? current(array_keys($currentNs)) : '';
$childName = strlen($prefix) > 1
? $prefix . ':' . $child->getName() : $child->getName();
// check if the value is string value / data
if (trim((string) $child) == '') {
$element = $parent->addChild($childName, null, $defaultNs);
} else {
$element = $parent->addChild(
$childName, htmlspecialchars((string)$child), $defaultNs
);
}
foreach ($child->attributes() as $attKey => $attValue) {
$element->addAttribute($attKey, $attValue);
}
foreach ($namespaces as $nskey => $nsurl) {
foreach ($child->attributes($nsurl) as $attKey => $attValue) {
$element->addAttribute($nskey . ':' . $attKey, $attValue, $nsurl);
}
}
// add children -- try with namespaces first, but default to all children
// if no namespaced children are found.
$children = 0;
foreach ($namespaces as $nskey => $nsurl) {
foreach ($child->children($nsurl) as $currChild) {
SimpleXMLElement_append($element, $currChild);
$children++;
}
}
if ($children == 0) {
foreach ($child->children() as $currChild) {
SimpleXMLElement_append($element, $currChild);
}
}
}
----
Server IP: 192.41.42.26
Probable Submitter: 153.104.168.157
----
Manual Page -- http://www.php.net/manual/en/class.simplexmlelement.php
Edit -- https://master.php.net/note/edit/108112
Del: integrated -- https://master.php.net/note/delete/108112/integrated
Del: useless -- https://master.php.net/note/delete/108112/useless
Del: bad code -- https://master.php.net/note/delete/108112/bad+code
Del: spam -- https://master.php.net/note/delete/108112/spam
Del: non-english -- https://master.php.net/note/delete/108112/non-english
Del: in docs -- https://master.php.net/note/delete/108112/in+docs
Del: other reasons-- https://master.php.net/note/delete/108112
Reject -- https://master.php.net/note/reject/108112
Search -- https://master.php.net/manage/user-notes.php