Skip to content

Instantly share code, notes, and snippets.

@tim-reynolds
Created February 10, 2015 22:11
Show Gist options
  • Save tim-reynolds/ac20289acdcfcde3633f to your computer and use it in GitHub Desktop.
Save tim-reynolds/ac20289acdcfcde3633f to your computer and use it in GitHub Desktop.
Bug in Magento's Varien_Simplexml_Element appendChild method
<?php
public function appendChild($source)
{
/* This is the bug
If an element has no children, only text, but has one or more attributes this call will evaluate to TRUE when it should
evaluate to FALSE.
The solution is simple. Wrap $source->children() in a call to count()
if (count($source->children()) {...
Note: This bug still exists in Magento 2 at this time.
Additional Note: This really is the fault of the messed up SimpleXMLElement class.
*/
if ($source->children()) {
/**
* @see http://bugs.php.net/bug.php?id=41867 , fixed in 5.2.4
*/
if (version_compare(phpversion(), '5.2.4', '<')===true) {
$name = $source->children()->getName();
}
else {
$name = $source->getName();
}
$child = $this->addChild($name);
} else {
$child = $this->addChild($source->getName(), $this->xmlentities($source));
}
$child->setParent($this);
$attributes = $source->attributes();
foreach ($attributes as $key=>$value) {
$child->addAttribute($key, $this->xmlentities($value));
}
foreach ($source->children() as $sourceChild) {
$child->appendChild($sourceChild);
}
return $this;
}
<?php
//Tim Reynolds @razialx 02/10/2015
//Don't actually run this, just illustrating a bug in Magento
$body = new Varien_Simplexml_Element('<outer></outer>');
$inner = new Varien_Simplexml_Element('<inner someAttribute="value does not matter">Some Text</inner>');
$body->appendChild($inner);
echo $body->asNiceXml();
<outer>
<inner someAttribute="value does not matter">Some Text</inner>
</outer>
<outer>
<inner someAttribute="value does not matter"/>
</outer>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment