PHP为什么不会这个JSON解码

时间:2015-02-08 01:49:35

标签: php json

已解决 - html_entity_decode 是解决方案

我的JSON没有解码。谁能发现我的错误?

JSON字符串如下所示:

{"ustaAddr":"1198 Industrial Way","ustaCity":"Carmel, CA","ustaPCode":"90210"}

以下是代码:

$newShipTo = stripslashes($aTrans['new_ship_to']);
if ($newShipTo != ""){
    $arrShipToAddr = json_decode($newShipTo, TRUE);
    $buyer_addr = $arrShipToAddr['ustaAddr'];
    $buyer_city = $arrShipToAddr['ustaCity'];
    $buyer_pcode= $arrShipToAddr['ustaPCode'];
    $shipTo_addr = 'TEST' . '<p>' .$buyer_addr. '</p><p>'.$buyer_city. '</p><p>'.$buyer_pcode. '</p>' ;
}

echo $shipTo_addr;

结果:

TEST

我也试过这个:

    $shipTo_addr = $arrShipToAddr['ustaAddr'] .' - '. $newShipTo;

结果:

- {"ustaAddr":"1198 Industrial Way","ustaCity":"Carmel, CA","ustaPCode":"90210"}

我也试过这个:

    $shipTo_addr = $arrShipToAddr->ustaAddr .' - '. $newShipTo;

结果:

- {"ustaAddr":"1198 Industrial Way","ustaCity":"Carmel, CA","ustaPCode":"90210"}

有人能发现我做错了吗?我看不到......


更新

json_decode()语句失败,但我不明白为什么。

$shipTo_addr = (is_array($arrShipToAddr)) ? 'yes' : 'no';

返回&#34;否&#34;


更新二:

我对文本字符串进行了硬编码(从上面的测试输出中复制/粘贴了屏幕结果!),它工作了! (当然,这不是解决方案,因为JSON字符串是在其他地方动态创建的,并且是从MySQL中检索的。)

$newShipTo = '{"ustaAddr":"1198 Industrial Way One","ustaCity":"Carmel, CA Two","ustaPCode":"90210 Free"}'; 
if ($newShipTo != ""){
    $arrShipToAddr = json_decode($newShipTo, TRUE);
    $shipTo_addr = (is_array($arrShipToAddr)) ? 'yes' : 'no';
}

结果:

yes

我也尝试过这些有前途的建议,但没有快乐:

$newShipTo = json_encode(stripslashes($aTrans['new_ship_to'])); //re-encode using PHP json_encode

$arrShipToAddr = json_decode(utf8_encode($newShipTo), TRUE); //force utf8

3 个答案:

答案 0 :(得分:0)

它对我有用,但你可以尝试:

$arrShipToAddr = json_decode(utf8_encode($newShipTo), TRUE);

答案 1 :(得分:0)

试试这个:

$newShipTo = '{"ustaAddr":"1198 Industrial Way","ustaCity":"Carmel, CA","ustaPCode":"90210"}';

然后可以将其解码为数组。

答案 2 :(得分:0)

嗯,伙计们,这里有人询问数据库中的字段类型是否有任何异常。

存储在字段中的数据是html_entitied(看起来像这样):

{\&quot;ustaAddr\&quot;:\&quot;1198 Industrial Way Here\&quot;,\&quot;ustaCity\&quot;:\&quot;Carmel, CA We\&quot;,\&quot;ustaPCode\&quot;:\&quot;90210 Go\&quot;}

但是,在使用stripslashesjson_decode之后,输出的字符串如下:

{"ustaAddr":"176 Industrial Drive","ustaCity":"Carmel, CA","ustaPCode":"90210"}

首先,我认为这是TEXT字段类型,并认为更改为VARCHAR是解决方案。不。

使用stripslashesjson_decode是不够的。要解决这个问题,我必须这样做:

$newShipTo = stripslashes(html_entity_decode($aTrans['new_ship_to']));

所以,完整的代码块:

$newShipTo = stripslashes(html_entity_decode($aTrans['new_ship_to']));
if ($newShipTo != ""){
    $arrShipToAddr = json_decode($newShipTo, TRUE);
    $buyer_addr = $arrShipToAddr['ustaAddr'];
    $buyer_city = $arrShipToAddr['ustaCity'];
    $buyer_pcode= $arrShipToAddr['ustaPCode'];
    $shipTo_addr = '<p>' .$buyer_addr. '</p><p>'.$buyer_city. '</p><p>'.$buyer_pcode. '</p>' ;
}