2011-04-07 135 views
0

我收到來自端點的API響應:如何從簡單的API響應中提取數據?

http://rest.sharethis.com/reach/getUrlInfo.php?url=「http://www.mydomain.com/」

{ "email" : { "inbound" : 47498, 
     "outbound" : "27459" 
    }, 
    "facebook" : { "inbound" : 6311, 
     "outbound" : "2301" 
    }, 
    "other" : { "inbound" : 2196, 
     "outbound" : "1456" 
    }, 
    "sharethis" : { "inbound" : 16536, 
     "outbound" : "7746" 
    }, 
    "total" : { "inbound" : 80399, 
     "outbound" : "40956" 
    }, 
    "twitter" : { "inbound" : 4946, 
     "outbound" : "1298" 
    } 
} 

我怎樣才能獲得的「入出境+」的總和「總「變量像一個字符串像$總回聲在PHP中。

+0

沒有問題,但是如果您無法找到如何使用PHP解析JSON以及如何訪問對象圖,那麼您不應該使用REST API,而應該首先掌握基本知識。 – Gordon 2011-04-07 08:43:01

+0

好吧,我不得不開始學習一天,我不知道它是JSON。我仍然在學習PHP。 – Sam 2011-04-07 08:59:23

+0

那麼,「開始學習」是好的,也許只是開始學習基礎知識吧) – Gordon 2011-04-07 09:04:27

回答

2
$decoded = json_decode($string); 
$inbound = $decoded->total->inbound; 
$outbound = $decoded->total->outbound; 
echo "Total: ".($inbound+$outbound); 
+0

這是php。在添加此php之前,我應該如何調用api響應。對不起,我對編碼很陌生。 – Sam 2011-04-07 09:00:59

+0

@sam,您用來獲取上述響應的代碼是什麼?或者你在問什麼?不是一個問題:-) – gmadd 2011-04-07 09:44:45

+0

我只是有我的網址。如何將JSON轉換爲字符串(可能使用cURL或get_contents),然後按照您所描述的解析它。 – Sam 2011-04-07 09:51:36

1

似乎是JSON。你應該檢查出json_decode(),這將把你的字符串變成一個PHP數組,可以用標準方式輕鬆操縱。