2009-05-07 3 views

답변

52
json_decode(json_encode((array) simplexml_load_string($obj)), 1); 
+0

영리한! 나는 그렇게 생각하지 않았을 것입니다. –

+3

가능하다면 100 upvotes를 주었을 것입니다. 그냥 굉장 :) –

+0

영리하면서도 읽기 쉽고 유지 보수가 용이하고 우아합니다. – Eddified

6

이 하나를 테스트하지 않았지만,이 그것을 끝낼 것 :

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

+0

이것은 나를 위해 작동하지 않습니다 –

+1

다른 사람이 "작동하지 않는"방법을 모르지만 모든 어린이와 특성을 반복하는 작업을 수행합니다. –

+0

CDATA를 읽지 못합니다. – reggie

0

에서 촬영. 이것은 부모 요소의 태그와 더 이상 자식이없는 요소의 태그 + 내용을 인쇄하는 재귀 함수입니다. 당신은 배열 구축을 변경할 수 있습니다 : SimpleXMLObject 단지 어쨌든 배열처럼 threated 할 수 있기 때문에 나는 지점이 표시되지 않는

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"; 
} 
0

...

을하지만, 당신이 정말 필요로하는 경우, 단지 chassagnette의 답변을 확인 포럼에서 this thread 또는 this post에 있습니다.

+2

세션에 저장하고 싶을 때를 제외하고, 'SimpleXMLElement'의 'Serialization is'은 ' '이 아닙니다. 따라서 배열로 캐스팅하는 것이 유용합니다. –

+0

@GromBeestje : XML이 이미 직렬화되었습니다. 세션에 문자열을 저장하는 데 아무런 문제가 없습니다. – hakre

+0

스크립트가로드 될 때마다 XML 문자열을 파싱하므로 구문 분석 된 양식을 저장하는 것이 좋습니다. –