2015-06-21 70 views
0

我對json和php的結合非常新,想知道爲什麼下面的代碼不工作。我的任務是逐個顯示標題項目。使用PHP顯示json飼料項的問題

<?php 
$json_string = file_get_contents("https://www.fiverr.com/gigs/gigs_as_json?host=search&type=single_query&query_string=pet&search_filter=rating&category_id=3&sub_category_id=49&limit=48"); 
$parsed_json = json_decode($json_string, true); 
$parsed_json = $parsed_json['gigs']; 

foreach($parsed_json as $key => $value) 
{ 
    echo $value['title'] . '<br>'; 
} 
?> 

下一個問題將通過,我將如何能夠保存圖像的項目叫cloud_img_med到我的服務器進入/抓起

您的幫助將不勝感激。

回答

1

要回答你關於爲什麼這個代碼不工作的問題:

我試圖設置它自己,發現out由file_get_contents獲取的輸出是壓縮的。你可以看到,通過讀取輸出一個簡單的var_dump:

var_dump($json_string); 

要解決這個問題,你需要使用自定義的背景下,沒有壓縮:

$context = stream_context_create(
    array(
     'http' => array(
      'method' => "GET", 
      'header' => "Accept-Encoding: gzip;q=0, compress;q=0\r\n", 
     ) 
)); 

然後把它作爲第三參數:

$json_string = file_get_contents("https://www.fiverr.com/gigs/gigs_as_json?host=search&type=single_query&query_string=pet&search_filter=rating&category_id=3&sub_category_id=49&limit=48", false, $context); 

我應該這樣做的JSON字符串可讀

0

該代碼似乎工作正常 - 我試圖在我的本地機器上。

運行此

<?php 
$str = <<<EOT 
// JSON here... 
EOT; 

$parsed_json = json_decode($str, true); 
$parsed_json = $parsed_json['gigs']; 

foreach($parsed_json as $key => $value) 
{ 
    echo $value['title'] . '<br>'; 
} 
?> 

給我這個輸出

replace the MGM lion with your pet or whoever<br>design creative Animal And Pet Company logo<br>` 

這是那種你想要什麼呢?如果您遇到問題,可能file_get_contents不允許在您的服務器上,並且無法獲得JSON。嘗試像我一樣將其硬編碼到$ str變量中,然後查看是否得到您想要的。

至於保存圖像,你可以在這裏檢查這個答案:https://stackoverflow.com/a/724449/4396258

+0

嗯不錯的觀察,我會檢查我的服務器上的file_get_contents權限:) –

0

我想問題可能是d ata你從Fiverr的JSON API獲得。至少在我的測試中,我發現它使用gzip編碼來壓縮您請求的數據。所以你必須解壓縮它。

$json_string = file_get_contents("https://www.fiverr.com/gigs/gigs_as_json?host=search&type=single_query&query_string=pet&search_filter=rating&category_id=3&sub_category_id=49&limit=48"); 
$content = json_decode(gzinflate(substr($json_string,10,-8))); 
$gigs = $content->gigs; 
foreach($gigs as $key => $value) 
{ 
    echo $value->title . '<br>'; 
}