Get JSON from URL by PHP
Asked Answered
P

4

3

I have a URL that returns a JSON object like this:

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

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

I want to get all of the urlPoster value and set in a array's element, and convert array to JSON so echo it.

How can I do it through PHP?

Prior answered 2/8, 2015 at 19:11 Comment(1)
have you tried json_decode()?Warpath
R
8
$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);
Rhamnaceous answered 2/8, 2015 at 19:22 Comment(0)
H
9

You can do something like that :

<?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>";
?>
Haiphong answered 2/8, 2015 at 19:16 Comment(0)
R
8
$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);
Rhamnaceous answered 2/8, 2015 at 19:22 Comment(0)
M
0

You can simply decode the json and then pick whatever you need:

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


]';

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

The output obviously is the URL stored in that property:

http://ia.media-imdb.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_UX34_CR0,0,34,50_AL_.jpg

BTW: "The Shawshank Redemption" is one of the best films ever made...

Meggie answered 2/8, 2015 at 19:16 Comment(0)
P
0

This how you do the same thing with array_map function.

<?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);
Pelagian answered 2/8, 2015 at 19:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.