2010-10-01 109 views
0

我想在PHP中使用json_decode()來解碼JSON字符串。我的部分JSON字符串中包含HTML標籤。例如。 (對於代碼的更好的視野去http://gist.github.com/605906使用json_decode()函數解碼html標籤

$json = '{"productid" : "prod:a8f2d4ef-108e-5fbf-fa74-595ddc0c7950","memo" : "<div style=\"color: #000000; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; background-image: initial; background-repeat: initial; background-attachment: initial; background-color: #ffffff; background-position: initial initial; margin: 8px;\">WS1CI metered clack valve, 1\" for softener  P/N: V1CIDME-03</div>"}'; 

But I am getting NULL values, when I do

var_dump(json_decode($json)); 

or

var_dump(json_decode($json, true)); 

回答

-3
<?php 
$arr = array(); 
$json = '{"productid" : "prod:a8f2d4ef-108e-5fbf-fa74-595ddc0c7950","memo" : "&lt;div style=\"color: #000000; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; background-image: initial; background-repeat: initial; background-attachment: initial; background-color: #ffffff; background-position: initial initial; margin: 8px;\"&gt;WS1CI metered clack valve, 1\" for softener P/N: V1CIDME-03&lt;/div&gt;"}'; 


var_dump(json_decode($json, true)); 

?> 

You need to transform all html (like <>&lt;&gt;

+0

這不回答這個問題。會發生什麼呢,'print_r'的結果被瀏覽器解釋爲HTML,所以結果*似乎是空的,但JSON解碼的對象仍然包含正確的字符串,它只是一些HTML不顯示任何東西。您的答案允許讓瀏覽器顯示實際的HTML代碼,但試圖將HTML轉義的字符串用於其他用途(例如創建DOM元素)可能不會產生預期結果。 – 2014-01-11 06:13:57

1

it works for me. If you get a specific error check your PHP installation, but As of PHP 5.2.0 Json comes by default.

object(stdClass)#99 (2) { 
    ["productid"]=> 
    string(41) "prod:a8f2d4ef-108e-5fbf-fa74-595ddc0c7950" 
    ["memo"]=> 
    string(59) "WS1CI metered clack valve, 1" for softener P/N: V1CIDME-03" 
} 
array(2) { 
    ["productid"]=> 
    string(41) "prod:a8f2d4ef-108e-5fbf-fa74-595ddc0c7950" 
    ["memo"]=> 
    string(59) "WS1CI metered clack valve, 1" for softener P/N: V1CIDME-03" 
} 

Works even for the html.

object(stdClass)#1 (2) { 
    ["productid"]=> 
    string(41) "prod:a8f2d4ef-108e-5fbf-fa74-595ddc0c7950" 
    ["memo"]=> 
    string(328) "<div style="color: #000000; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; background-image: initial; background-repeat: initial; background-attachment: initial; background-color: #ffffff; background-position: initial initial; margin: 8px;">WS1CI metered clack valve, 1" for softener P/N: V1CIDME-03</div>" 
} 
0

Have a look at your server's error_log. This might yield to some more information.