2015-08-02 3 views
2

У меня есть URL-адрес, который возвращает объект JSON как это:Получить JSON из URL с помощью PHP

[ 
    { 
     "idIMDB": "tt0111161", 
     "ranking": 1, 
     "rating": "9.2", 
     "title": "The Shawshank Redemption", 
     "urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/[email protected]_V1_UX34_CR0,0,34,50_AL_.jpg", 
     "year": "1994" 
    } 
] 

URL: http://www.myapifilms.com/imdb/top

Я хочу, чтобы получить все значения urlPoster и установить в элементе массива , и преобразовать массив в JSON, чтобы его эхо.

Как я могу это сделать через PHP?

+0

Вы пробовали 'json_decode()'? – Sayed

ответ

5
$json = file_get_contents('http://www.myapifilms.com/imdb/top'); 

$array = json_decode($json); 

$urlPoster=array(); 
foreach ($array as $value) { 
    $urlPoster[]=$value->urlPoster; 
} 

print_r($urlPoster); 
0

Вы можете просто декодировать JSON, а затем выбрать то, что вам нужно:

<?php 
$input = '[ 
     { 
       "idIMDB": "tt0111161", 
       "ranking": 1, 
       "rating": "9.2", 
       "title": "The Shawshank Redemption", 
       "urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/[email protected]_V1_UX34_CR0,0,34,50_AL_.jpg", 
       "year": "1994" 
     } 


]'; 

$content = json_decode($input); 
$urlPoster = $content[0]->urlPoster; 
echo $urlPoster; 

Выходной сигнал, очевидно, является URL хранится в этой собственности:

http://ia.media-imdb.com/images/M/[email protected]_V1_UX34_CR0,0,34,50_AL_.jpg

КСТАТИ: «The Шоушенке Redemption "является одной из лучших фильмов, когда-либо сделанных ...

8

Вы можете сделать некоторые вещи, как, что:

<?php 
$json_url = "http://www.myapifilms.com/imdb/top"; 
$json = file_get_contents($json_url); 
$data = json_decode($json, TRUE); 
echo "<pre>"; 
print_r($data); 
echo "</pre>"; 
?> 
0

Это, как вы делаете то же самое с array_map функции.

<?php 

#function to process the input 
function process_input($data) 
{ 
return $data->urlPoster; 
} 

#input url 
$url = 'http://www.myapifilms.com/imdb/top'; 


#get the data 
$json = file_get_contents($url); 

#convert to php array 
$php_array = json_decode($json); 

#process the data and get output 
$output = array_map("process_input", $php_array); 


#convert the output to json array and print it 
echo json_encode($output); 
Смежные вопросы