sam
sam

Reputation: 1087

Parse a string containing a query string and access a specific value

I am fetching some API data with cURL and it returns the output in following string:

$response = "oauth_token=xxx&oauth_token_secret=yyy&oauth_expires_in=3600&xoauth_request_auth_url=https%3A%2F%2Fapi.login.yahoo.com%2Foauth%2Fv2%2Frequest_auth%3Foauth_token%3Dxxx&oauth_callback_confirmed=true";

How can I get the values for each of the key from the above string, for example I want to get the xoauth_request_auth_url value. Currently I'm doing it in following way:

$arr = explode('&', $response);

$url = $arr[3];     
$url = explode('=', $url);

$xoauth_request_auth_url = $url[1]; //final result

My questions:

  1. Is there an efficient way to get the above value (I'm afraid above method will not work if there's an & in any of the variable vlaue)?

  2. How can I convert the URl value into url format? For example currently it is:

https%3A%2F%2Fapi.login.yahoo.com

I would like to convert it into:

https://api.login.yahoo.com

Upvotes: 0

Views: 94

Answers (3)

Elentriel
Elentriel

Reputation: 1237

http://php.net/manual/en/function.parse-str.php

or you can build your own function (i can give you guidelines should parse-str not cover your needs)

as for your second question,it also answers part of the first. Uri components are being encoded and therefore you will not find (or should not find) an actual & character. Like wise to decode url's. use http://php.net/manual/en/function.urldecode.php and to encode its function pair urlencode

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

parse_str() to parse a URL query string into an array and urldecode() to get the decoded characters:

parse_str($response, $array);
$array = array_map('urldecode', $array);

print_r($array);

Yields:

Array
(
    [oauth_token] => xxx
    [oauth_token_secret] => yyy
    [oauth_expires_in] => 3600
    [xoauth_request_auth_url] => https://api.login.yahoo.com/oauth/v2/request_auth?oauth_token=xxx
    [oauth_callback_confirmed] => true
)

Upvotes: 1

Mikel Bitson
Mikel Bitson

Reputation: 3627

Use parse_str, like so:

$values = array();
parse_str($response, $values);
var_dump($values);

Also, if you need to remove the URL encoded characters from any of the values, use urldecode.

Upvotes: 3

Related Questions