eng.let
eng.let

Reputation: 37

How to print an array element from JSON into PHP

If you access the webpage https://api.mercadolibre.com/items/MLB752465575 you will receive a JSON response. All I need to start is print the item "id" on the screen.

This is my code:

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
  </head>
  <body>
  <?php

    $json_str = "https://api.mercadolibre.com/items/MLB752465575";

    $obj = json_decode($json_str);

    echo "id: $obj->id<br>"; 

  ?>
  </body>
</html>

All I want is receive the MLB752465575 part into my browser.

How can I do it?

Upvotes: 2

Views: 90

Answers (3)

Patrick Simard
Patrick Simard

Reputation: 2375

$json_str = "https://api.mercadolibre.com/items/MLB752465575";

The above does not retrieve the data it's saving the url to the var and that's not what you want.

You just need to fetch the content You can use cURL or file_get_contents()

cURL version:

<?php

$url = "https://api.mercadolibre.com/items/MLB752465575";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$r = curl_exec($curl);
curl_close($curl);
$array = json_decode($r, true);

echo "<pre>";
print_r($array);
echo "</pre>";

?>

file_get_contents version:

<?php
$r = file_get_contents('https://api.mercadolibre.com/items/MLB752465575');

echo "<pre>";
echo print_r(json_decode($r, true));
echo "</pre>";
?>

Both of them will work unless the remote website requires you to be human (has extra verifications to stop robot requests). cURL would be a better way if that were the case because you can fake a user agent using a header array.

Once you have the array build it's just a matter of accessing the required data. using $r as an array result of the remote json structure.

Upvotes: 3

Scott C Wilson
Scott C Wilson

Reputation: 20016

Use curl to get the result, and json_decode to turn it into an array.

<?php
$url = "https://api.mercadolibre.com/items/MLB752465575";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpcode != 200) {
      echo "error " . $httpcode;
      curl_close($ch);
      return -1;
}
$result_arr = json_decode($result, true);
echo $result_arr['id'];
curl_close($ch);

Upvotes: 1

Steve Chamaillard
Steve Chamaillard

Reputation: 2339

$jsonResponse = file_get_contents('https://api.mercadolibre.com/items/MLB752465575');
$obj = json_decode($jsonResponse);

echo "id: {$obj->id}<br>";

What you did in your code was to json_decode the URL itself. You needed to get the content from the URL, and then decode the content.

Upvotes: 0

Related Questions