$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
//$array = json_decode($json,TRUE);
目前共有7篇帖子。
![]() |
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml); //$array = json_decode($json,TRUE); |
![]() |
案例:
$xml = '<?xml version="1.0" encoding="utf-8"?><root><a/><b>text</b><c name="value" /><d name="value">text</d><e><a>text1</a><b>text2</b></e><f><a>text1</a><a>text2</a></f><g>text1<a>text2</a></g></root>'; $xmldoc = simplexml_load_string($xml); $json = json_encode($xmldoc); echo $json; 輸出結果: {"a":{},"b":"text","c":{"@attributes":{"name":"value"}},"d":"text","e":{"a":"text1","b":"text2"},"f":{"a":["text1","text2"]},"g":"text1"} <?xml version="1.0" encoding="utf-8"?> <root> <a/> <b>text</b> <c name="value" /> <d name="value">text</d> <e> <a>text1</a> <b>text2</b> </e> <f> <a>text1</a> <a>text2</a> </f> <g> text1 <a>text2</a> </g> </root> |
![]() |
可見json_encode編碼XML還是有bug的。至少d標籤的屬性丟失了,g標籤下的a標籤全部丟失了
|
![]() |
<?php
$xml = '<?xml version="1.0" encoding="utf-8"?><root><node id="15">E</node></root>'; $xmldoc = simplexml_load_string($xml); $json = json_encode($xmldoc); echo $json; ?> 輸出結果:{"node":"E"} 可見id屬性被丟掉了 |
![]() |
http://php.net/manual/en/function.json-encode.php
4 Ray.Paseur often uses Gmail ¶7 months ago If you're wondering whether a JSON string can be an analog of an XML document, the answer is probably "nope." XML supports attributes, but JSON does not. A JSON string generated by json_encode(), when called on a SimpleXML object, will not have the attributes and no error or exception will issue - the original data will simply be lost. To see this in action: <?php error_reporting(E_ALL); echo '<pre>'; // STARTING FROM XML $xml = <<<EOD <?xml version="1.0" ?> <ingredients> <ingredient> <name>tomatoes</name> <quantity type="cup">4</quantity> </ingredient> <ingredient> <name>salt</name> <quantity type="tablespoon">2</quantity> </ingredient> </ingredients> EOD; // CREATES AN ARRAY OF SimpleXMLElement OBJECTS $obj = SimpleXML_Load_String($xml); var_dump($obj); echo PHP_EOL; // SHOW THE ATTRIBUTES HIDDEN IN THE SimpleXMLElement OBJECTS foreach ($obj as $sub) { echo PHP_EOL . (string)$sub->quantity . ' ' . (string)$sub->quantity['type']; } echo PHP_EOL; // USING THE OBJECT, CREATE A JSON STRING $jso = json_encode($obj); echo htmlentities($jso); // 'type' IS LOST echo PHP_EOL; PHP官網上的一個user contributed note 也提到了type屬性丟失 |
![]() |
所以,如果用了這種方法轉換,那麼在XML中應該避免使用以下格式:
<e name="value">text</e> <e> text <a>text</a> </e> |
![]() |