在XML中获取Json值 - PHP

时间:2014-02-12 15:43:50

标签: php xml json

说我有以下php:

$Url = sprintf( "http://www.wowhead.com/item=%u?xml", $EntryId );
$Xml = file_get_contents( $Url );   
//echo htmlentities($Xml, ENT_COMPAT, 'UTF-8');     
$Xml = simplexml_load_string( $Xml);

让我们说这是xml:

http://www.wowhead.com/item=31065?xml

我知道如果T想说我可以做DisplayID:

$DisplayId = $Xml->item->icon["displayId"];

但是我想获取文件<json>部分内的值。

<json>
    <![CDATA[
    "armor":464,"classs":4,"displayid":117596,"id":31064,"level":146,"name":"3Hood of         Absolution","reqclass":16,"reqlevel":70,"slot":1,"slotbak":1,"source":[5],"sourcemore":    [{"n":"Tydormu","t":1,"ti":23381}],"specs":[258],"subclass":1
    ]]>
</json>

我想获得slotbak值,但我不确定该怎么做。我做echo htmlentities($Xml, ENT_COMPAT, 'UTF-8');以确保我的xml文件正常,我就是。但是,当我使用json_decodejson_encode时,它往往只返回{ } { } { }或简单地返回对象而不是值。

有谁知道我该怎么做?

1 个答案:

答案 0 :(得分:1)

您需要删除<![CDATA[]]>以使json_decode生效。

试试这个:

$json = $Xml->item->json;

$cleanedJson = str_ireplace(array('<![CDATA[', ']]>'), array('{', '}'),  $json);

$jsonObject = json_decode($cleanedJson);