-1

I need help to get a string from a json http response using php. The json contains 2 sets of data with curly brackets mark. Here is what the response looks like

{ "token": "579ca74b-d82a-4c17-aff6-60f440680541", "redirect_url": "https://app.sandbox.midtrans.com/snap/v2/vtweb/579ca74b-d82a-4c17-aff6-60f440680541" }

the token and url will not the same for each user and they will have different length. I need to obtain the url only(as a string) without those brackets, commas, double quotes, and labels.I've put the response result in a variable and I've tried using str_replace but I'm not sure how to do it correctly because the token is dynamic. can anyone help me, please?

<?php
$unnecessary = array('{', '}', '"', 'token:', 'redirect_url');

$new = str_replace($unnecessary, "", $old)

?>
Wira Xie
  • 819
  • 5
  • 24
  • 46

2 Answers2

2

I need to obtain the url only

$json = json_decode($json_str, true);
$url = $json['redirect_url'];
2

Simply decode JSON string and take the values you need:

<?php
$jsonString = '
  {
    "token": "579ca74b-d82a-4c17-aff6-60f440680541",
    "redirect_url": "https://app.sandbox.midtrans.com/snap/v2/vtweb/579ca74b-d82a-4c17-aff6-60f440680541"
  }
';

$json = json_decode($jsonString);

echo $json->token;
echo $json->redirect_url;
Krzysztof Raciniewski
  • 4,735
  • 3
  • 21
  • 42