目前共有7篇帖子。 內容轉換:不轉換▼
 
點擊 回復
174 6
json_encode除了可以對數組進行編碼外,還可以對XML對象進行編碼
一派護法 十九級
1樓 發表于:2015-4-25 22:27
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
//$array = json_decode($json,TRUE);
一派護法 十九級
2樓 發表于:2015-4-25 22:32
案例:
$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>
一派護法 十九級
3樓 發表于:2015-4-25 22:35
可見json_encode編碼XML還是有bug的。至少d標籤的屬性丟失了,g標籤下的a標籤全部丟失了
一派護法 十九級
4樓 發表于:2015-4-25 22:38
<?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屬性被丟掉了
一派護法 十九級
5樓 發表于:2015-4-25 22:45
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屬性丟失
一派護法 十九級
6樓 發表于:2015-4-26 00:33
所以,如果用了這種方法轉換,那麼在XML中應該避免使用以下格式:
<e name="value">text</e>
<e> text <a>text</a> </e>
一派護法 十九級
7樓 發表于:2015-4-26 00:33

回復帖子

內容:
用戶名: 您目前是匿名發表
驗證碼:
(快捷鍵:Ctrl+Enter)
 

本帖信息

點擊數:174 回複數:6
評論數: ?
作者: 巨大八爪鱼
最後回復:巨大八爪鱼
最後回復時間:2015-4-26 00:33
 
©2010-2024 Arslanbar Ver2.0
除非另有聲明,本站採用創用CC姓名標示-相同方式分享 3.0 Unported許可協議進行許可。