2011-12-14 120 views
0

我試圖從API解析json響應,但購買改變了我創建的一些現有的PHP代碼,但是我有困難。這是JSON響應解析來自API的json響應與PHP

"response":{ 
    "status":"ok", 
    "userTier":"free", 
    "total":10, 
    "startIndex":1, 
    "pageSize":10, 
    "currentPage":1, 
    "pages":1, 
    "results":[{ 
    "id":"lifeandstyle/series/cycling", 
    "type":"series", 
    "webTitle":"Cycling", 
    "webUrl":"http://www.guardian.co.uk/lifeandstyle/series/cycling", 
    "apiUrl":"http://content.guardianapis.com/lifeandstyle/series/cycling", 
    "sectionId":"lifeandstyle", 
    "sectionName":"Life and style" 
    } 

試圖將「webTitle」和「WEBURL」部分

<?php 
require_once 'Zend/Json.php'; 
$val = Zend_Json::decode($result); 
$arr = $val; 
if(preg_match_all("~<p>([\s\S]*?)</p>~i", $arr['parse']['text']['*'], $matches)){ 
if(is_array($matches[1])) foreach($matches[1] as $paragraph){ 
echo $paragraph; 
} 
} 
?> 

此代碼只是在解析p標籤內容中解析所有的信息,我會如何改變呢?

謝謝

回答

0

你是什麼意思解析? JSON回覆只要您解碼就可以立即使用。你沒有$arr['parse']...你有$arr['webTitle']其中包含「騎自行車」。你想在「騎車」裏解析什麼?

此外,將結果分配給$ val然後將$ val分配給$ arr會產生什麼結果?直接分配給$ arr。

做print_r($ val)並看看你有什麼。這會讓你更清楚你需要做什麼。你很可能使事情比他們需要的更復雜。

2

我不是你的問題100%明確。 Zend_Json :: decode使用json_decode,這是@psion所指的。我認爲$在你的榜樣

$val = Zend_Json::decode($result); 

擁有您事先粘貼的J​​SON結果

它看起來像你對我張貼的JSON是無效的,或者至少不完全(因爲缺少],而遺漏})。我不確定這與解析標籤有什麼關係,但無論如何,這裏是一個解析json並提取您感興趣的組件的示例。它剝離了從響應中的前導「響應」:位json在解碼之前也是如此。

<?php 
$sJson = '"response":{ 
    "status":"ok", 
    "userTier":"free", 
    "total":10, 
    "startIndex":1, 
    "pageSize":10, 
    "currentPage":1, 
    "pages":1, 
    "results":[{ 
    "id":"lifeandstyle/series/cycling", 
    "type":"series", 
    "webTitle":"Cycling", 
    "webUrl":"http://www.guardian.co.uk/lifeandstyle/series/cycling", 
    "apiUrl":"http://content.guardianapis.com/lifeandstyle/series/cycling", 
    "sectionId":"lifeandstyle", 
    "sectionName":"Life and style" 
    }]}'; 
$sJson = substr($sJson, strpos($sJson, ':') + 1); 

// feel free to replace json_decode w/ Zend_Json::decode 
$aNative = json_decode($sJson); 

$sWebTitle = $aNative->results[0]->webTitle; 
$sWebUrl = $aNative->results[0]->webUrl; 

echo 'Web Title: ' . $sWebTitle . PHP_EOL; 
echo 'Web URL : ' . $sWebUrl . PHP_EOL; 

下面是從腳本輸出

Web Title: Cycling 
Web URL : http://www.guardian.co.uk/lifeandstyle/series/cycling