1

I have code:

$json = file_get_contents('https://api.coinmarketcap.com/v1/ticker/?limit=0');
$coins = json_decode($json, true);
foreach($coins as $coin) {
  echo $coin->24h_volume_usd;
}

Script return me error:

Parse error: syntax error, unexpected '24' (T_LNUMBER), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'...

Yes, I know I can't used name JSON with number, but I can't change 24h_volume_usd to for example: h_volume_usd, because this is value download from other page (ink).

4
  • Change the object to an array? Perhaps that will work? You can do that with json_decode(), but that part is missing from your code. Commented Jan 21, 2018 at 21:02
  • @KIKOSoftware Not work, when I change to: echo $coin['24h_volume_usd']; I have error: Cannot use object of type stdClass as array Commented Jan 21, 2018 at 21:04
  • You need to change the object to an array, of course. For instance like Aniket Sahrawat says. Commented Jan 21, 2018 at 21:05
  • it's version PHP 7.2. I added code to my answer. Commented Jan 21, 2018 at 21:07

2 Answers 2

2

When an object key starts with digits, you need to wrap it as string literal in braces, like this:

$coin->{"24h_volume_usd"};
Sign up to request clarification or add additional context in comments.

Comments

1

You can decode the json-string into an associative array, by setting the second parameter to true.

$coins = json_decode($jsonString, true);
foreach($coins as $coin) {
  echo $coin['24h_volume_usd'];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.