V
V
Vanzent2020-09-12 16:45:10
PHP
Vanzent, 2020-09-12 16:45:10

Extract value from json?

When checking the recaptcha on the server, a response comes from Google:

{"success": false,"error-codes": ["invalid-input-response" ]}

Next, decoding the json response:
$recaptcha = json_decode($recaptcha);

I do
var_dump($recaptcha):
object(stdClass)#6 (2) {
  ["success"]=>
  bool(false)
  ["error-codes"]=>
  array(1) {
    [0]=>
    string(22) "invalid-input-response"
  }
}

I get the value for 'success' like this:
$recaptcha->success
I can't get the value of 'invalid-input-response'
So it $recaptcha->error-codesoutputs 0 and the integer type
So the same How to do it, tell me? $recaptcha->error-codes[0]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alexalexes, 2020-09-12
@Vanzent

The problem is getting around the invalid property name (because a hyphen is used).
We use the magic of naming a class property through a variable.

$recaptcha_property_name = 'error-codes';
echo $recaptcha->$recaptcha_property_name[0];

I
Ilya, 2020-09-12
@New_Horizons

Either like this:

$recaptcha = json_decode($recaptcha, true);
echo $recaptcha['error-codes'][0];

Either like this:
$recaptcha = json_decode($recaptcha);
echo $recaptcha->{'error-codes'}[0];

Reading about the second argument of the json_decode function

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question