phptext-extractionquerystringparameterurl-parsing

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


Solution

  • 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
    )