-5
得到JSON這是我的XML字符串:如何從XML字符串
<root>EXTRA
<elem id="123" at="abc">HelloText</elem>
</root>
我怎樣才能將其轉換爲一個JSON格式(帶屬性和HelloText)?
得到JSON這是我的XML字符串:如何從XML字符串
<root>EXTRA
<elem id="123" at="abc">HelloText</elem>
</root>
我怎樣才能將其轉換爲一個JSON格式(帶屬性和HelloText)?
因爲RJS並不想檢查我建議他答案,這裏是從this post:
一個常見的錯誤是忘記json_encode()不尊重與textvalue和屬性的元素(S )。它會選擇其中的一個,意思是dataloss。下面的功能解決了這個問題。如果決定採用json_encode/decode方式,建議使用以下函數。通過這樣做
function json_prepare_xml($domNode){
foreach($domNode->childNodes as $node)
if($node->hasChildNodes()) json_prepare_xml($node);
if($domNode->hasAttributes() && strlen($domNode->nodeValue)){
$domNode->setAttribute("nodeValue", $node->textContent);
$node->nodeValue = "";
}
return $node;
}
$dom->loadXML(file_get_contents($xmlfile));
json_prepare_xml($dom);
$sxml = simplexml_load_string($dom->saveXML());
$json = json_decode(json_encode($sxml)));
,<foo bar="3">Lorem</foo>
不會最終在你的JSON {"foo":"Lorem"}
。
@RJS downvotes可能是因爲這是一個脫離主題的問題。請參閱[help/on-topic]要點#4 –
http://stackoverflow.com/questions/8830599/php-convert-xml-to-json – geekido
@RJS,你是否從這裏發現了拯救編碼的答案? http://stackoverflow.com/questions/8830599/php-convert-xml-to-json我認爲這是適合你的情況。 – bksi