2016-12-08 6 views
1

SimpleXML을 사용하여 XML을 JSON으로 변환하는 방법을 알고 있지만 같은 노드에 여러 종류의 자식이있는 경우 어떻게 주문 정보를 유지할 수 있습니까?PHP는 혼합 배열 자식을 사용하여 JSON에서 자식 순서를 유지하도록 변환합니다.

$xml = simplexml_load_string(' 
<root> 
    <a id="0"></a> 
    <b id="0"></b> 
    <b id="1"></b> 
    <a id="1"></a> 
    <a id="2"></a> 
</root> 
'); 
echo json_encode($xml->children()); 

코드 인쇄 일 아래 : 따라서

{ 
    "a": [ 
    { 
     "@attributes": { 
     "id": "0" 
     } 
    }, 
    { 
     "@attributes": { 
     "id": "1" 
     } 
    }, 
    { 
     "@attributes": { 
     "id": "2" 
     } 
    } 
    ], 
    "b": [ 
    { 
     "@attributes": { 
     "id": "0" 
     } 
    }, 
    { 
     "@attributes": { 
     "id": "1" 
     } 
    } 
    ] 
}  

내가 요소가있는 경우 순서대로 a, b, b, a, a 또는

a, a, b, b, a 그래서 궁금 여부, 출신 어디에 알 수 없습니다 XML을 JSON으로 변환하여이 정보를 유지하는 방법? 아마 결과는 다음과 같습니다

[ 
    { 
    "tag": "a", 
    "@attributes": { 
     "id": "0" 
    } 
    }, 
    { 
    "tag": "b", 
    "@attributes": { 
     "id": "0" 
    } 
    }, 
    { 
    "tag": "b", 
    "@attributes": { 
     "id": "1" 
    } 
    }, 
    { 
    "tag": "a", 
    "@attributes": { 
     "id": "1" 
    } 
    }, 
    { 
    "tag": "a", 
    "@attributes": { 
     "id": "2" 
    } 
    } 
]  

답변

1
$xml = <<<'XML' 
<root> 
    <a id="0"></a> 
    <b id="0"></b> 
    <b id="1"></b> 
    <a id="1"></a> 
    <a id="2"></a> 
</root> 
XML; 

$xe = simplexml_load_string($xml); 
$a = $xe->xpath('*'); 
$a = array_map(function ($e) { 
    $item = (array) $e; 
    $item['tag'] = $e->getName(); 
    return $item; 
}, $a); 
echo json_encode($a, JSON_PRETTY_PRINT); 

출력

[ 
    { 
     "@attributes": { 
      "id": "0" 
     }, 
     "tag": "a" 
    }, 
    { 
     "@attributes": { 
      "id": "0" 
     }, 
     "tag": "b" 
    }, 
    { 
     "@attributes": { 
      "id": "1" 
     }, 
     "tag": "b" 
    }, 
    { 
     "@attributes": { 
      "id": "1" 
     }, 
     "tag": "a" 
    }, 
    { 
     "@attributes": { 
      "id": "2" 
     }, 
     "tag": "a" 
    } 
] 
+0

많은 감사합니다! 하지만 XML에 네임 스페이스가 있다면 어떨까요? xpath는 빈 배열을 반환하고 –

+0

@ I2_wadxm을 반환합니다. 별표는 네임 스페이스가 적용된 XML에서도 작동합니다. [예] (https://eval.in/693481). 그러나 SimpleXML 대신 DOM 확장을 사용할 수 있습니다. ['DOMXPath'] (http://php.net/manual/en/class.domxpath.php)는 네임 스페이스를 등록 할 수 있습니다 :'$ xp-> registerNamespace ('myns', 'http : // ...') ;', 그런 다음 XPath 표현식 :'/ root/myns : *'에서 사용하십시오. –

0

그냥 자식들에 대해 반복하고 각 요소에 tag를 설정합니다. 이런 식으로 뭔가 :

$result = []; 
foreach($xml->children() as $tag => $e) { 
    $tagged = json_decode(json_encode($e)); 
    $tagged->tag = $tag; 
    $result[] = $tagged; 
} 
echo json_encode($r);