Import external URL array with PHP

Asked

Viewed 155 times

0

That link https://api.coinmarketcap.com/v1/ticker/ generates an array, I would like to import it into a local array, as I do ?

I tried to make:

$url = "https://api.coinmarketcap.com/v1/ticker/";

function curl_get_contents($url) {
    $ch = curl_init();
    $timeout = 5;

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

    $data[] = curl_exec($ch);

    curl_close($ch);

    return $data;
}

$contents = curl_get_contents($url);

echo count($contents); // 1

But only one index is created with all arrays inside it, the result is 1, I would like to keep the count number of $Contents for the number of indexes of the URL.

1 answer

2


This content is in JSON, missed you decode. Do so:

$contents = json_decode(curl_get_contents($url));
print_r($contents);

This will generate an array of objects. If you need an array of (associative) arrays, pass true for Coder in the second argument:

$contents = json_decode(curl_get_contents($url), true);
  • It is generating this in front of the Dice: [0] => stdClass Object, and I cannot use the array within foreach($Contents as $k => $y) { }

  • See the update above

Browser other questions tagged

You are not signed in. Login or sign up in order to post.