2012-05-17 118 views
1

所以我有以下的PHP字符串:PHP複雜字符串解析,JSON'able?

$output = {"playerId":1178,"percentChange":0.1,"averageDraftPosition":260,"percentOwned":0.1,"mostRecentNews":{"news":"Accardo was called up from Columbus on Monday, the Indians' official Twitter feed reports.","spin":"He'll replace Dan Wheeler on the active roster after carrying a 2.76 ERA over 13 appearances with the Clippers to start the season.","date":"Mon May 14"},"fullName":"Jeremy Accardo"} 

我需要的是:「阿卡多是從哥倫布週一,印第安人的官方Twitter的飼料報道叫了起來」和「在與快船開始本賽季13次出場後,他將在主動陣容中替換Dan Wheeler。」作爲子串。但我似乎無法弄清楚最好和最優雅的方式來做到這一點。我試圖對JSON_decode字符串進行解碼,但沒有返回任何內容。有任何想法嗎? (我正在使用PHP)

+2

你能給我們一段你正在用來解析它的代碼嗎?另外,請注意,json_decode有第二個變量,可以讓你選擇它是一個數組還是一個對象。 – Odinn

+0

@ sfgiants2010您的json數據包含許多未轉義的單引號,我已修復它,檢查我的答案。 –

回答

1

你有幾個未轉義的字符串,這是導致錯誤。一個簡單的格式可以節省您的時間。

$output = '{ 
    "playerId":1178, 
    "percentChange":0.1, 
    "averageDraftPosition":260, 
    "percentOwned":0.1, 
    "mostRecentNews": { 
     "news":"Accardo was called up from Columbus on Monday, the Indians official Twitter feed reports", 
     "spin":"Hell replace Dan Wheeler on the active roster after carrying a 2.76 ERA over 13 appearances with the Clippers to start the season.", 
     "date":"Mon May 14" 
    }, 
    "fullName":"Jeremy Accardo" 
}'; 
$json = json_decode($output); 
0

你試過這個嗎?

$output = '{"playerId":1178,"percentChange":0.1,"averageDraftPosition":260,"percentOwned":0.1,"mostRecentNews":{"news":"Accardo was called up from Columbus on Monday, the Indians\' official Twitter feed reports.","spin":"He\'ll replace Dan Wheeler on the active roster after carrying a 2.76 ERA over 13 appearances with the Clippers to start the season.","date":"Mon May 14"},"fullName":"Jeremy Accardo"}'; 

$array = json_decode($output, true); 

echo $array['mostRecentNews']['news']; 
echo $array['mostRecentNews']['spin']; 
2

這不是string。嘗試是這樣的:

$output = '{"playerId":1178,"percentChange":0.1,"averageDraftPosition":260,"percentOwned":0.1,"mostRecentNews":{"news":"Accardo was called up from Columbus on Monday, the Indians\' official Twitter feed reports.","spin":"He\'ll replace Dan Wheeler on the active roster after carrying a 2.76 ERA over 13 appearances with the Clippers to start the season.","date":"Mon May 14"},"fullName":"Jeremy Accardo"}'; 

$object = json_decode($output); 
$array = json_decode($output, true); 
$string = json_encode($array); 
0

json_encode只帶有UTF8。你用utf8使用allthings嗎?你有synstax錯誤。如果你手動定義json變量,它可能是這樣的;

<?php 
$output=<<<JSONSTR 
{"playerId":1178,"percentChange":0.1,"averageDraftPosition":260,"percentOwned":0.1,"mostRecentNews":{"news":"Accardo was called up from Columbus on Monday, the Indians' official Twitter feed reports.","spin":"He'll replace Dan Wheeler on the active roster after carrying a 2.76 ERA over 13 appearances with the Clippers to start the season.","date":"Mon May 14"},"fullName":"Jeremy Accardo"} 
JSONSTR; 
$variable = json_decode($output); 
var_dump($variable); 
?>