سؤال

ولست بحاجة للادلاء متكرر على PHP SimpleXMLObject إلى صفيف. والمشكلة هي أن كل عنصر فرعي هو أيضا PHP SimpleXMLElement.

هل هذا ممكن؟

هل كانت مفيدة؟

المحلول

json_decode(json_encode((array) simplexml_load_string($obj)), 1);

نصائح أخرى

ولم اختبار هذا واحد، ولكن هذا يبدو لانجاز ذلك:

function convertXmlObjToArr($obj, &$arr) 
{ 
    $children = $obj->children(); 
    foreach ($children as $elementName => $node) 
    { 
        $nextIdx = count($arr); 
        $arr[$nextIdx] = array(); 
        $arr[$nextIdx]['@name'] = strtolower((string)$elementName); 
        $arr[$nextIdx]['@attributes'] = array(); 
        $attributes = $node->attributes(); 
        foreach ($attributes as $attributeName => $attributeValue) 
        { 
            $attribName = strtolower(trim((string)$attributeName)); 
            $attribVal = trim((string)$attributeValue); 
            $arr[$nextIdx]['@attributes'][$attribName] = $attribVal; 
        } 
        $text = (string)$node; 
        $text = trim($text); 
        if (strlen($text) > 0) 
        { 
            $arr[$nextIdx]['@text'] = $text; 
        } 
        $arr[$nextIdx]['@children'] = array(); 
        convertXmlObjToArr($node, $arr[$nextIdx]['@children']); 
    } 
    return; 
} 

http://www.codingforums.com/showthread.php؟t= 87283

ومن الممكن. هذه هي وظيفة العودية التي تطبع العلامات من عناصر الأم والبطاقات + محتويات العناصر التي ليس لها المزيد من الأطفال. يمكنك تغييرها لبناء صفيف:

foreach( $simpleXmlObject as $element )
{
    recurse( $element );
}

function recurse( $parent )
{
    echo '<' . $parent->getName() . '>' . "\n";    

    foreach( $parent->children() as $child )
    {
        if( count( $child->children() ) > 0 )
        {
            recurse( $child );
        }
        else
        {
           echo'<' . $child->getName() . '>';
           echo  iconv( 'UTF-8', 'ISO-8859-1', $child );
           echo '</' . $child->getName() . '>' . "\n";
        }
    }

   echo'</' . $parent->getName() . '>' . "\n";
}

وأنا لا أرى هذه النقطة منذ SimpleXMLObject يمكن threated تماما مثل المصفوفات على أي حال ...

ولكن إذا كنت حقا بحاجة إلى ذلك، والتحقق من مجرد الإجابة chassagnette للفي هذا الموضوع أو هذا المنصب في المنتدى.

واعتمادا على بعض المشاكل مع CDATA، صفائف الخ (انظر: SimpleXMLElement إلى PHP صفيف )

وأعتقد، وهذا سيكون أفضل حل:

public function simpleXml2ArrayWithCDATASupport($xml)
{
    $array = (array)$xml;

    if (count($array) === 0) {
        return (string)$xml;
    }

    foreach ($array as $key => $value) {
        if (is_object($value) && strpos(get_class($value), 'SimpleXML') > -1) {
            $array[$key] = $this->simpleXml2ArrayWithCDATASupport($value);
        } else if (is_array($value)) {
            $array[$key] = $this->simpleXml2ArrayWithCDATASupport($value);
        } else {
            continue;
        }
    }

    return $array;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top