mike20132013
mike20132013

Reputation: 5425

How to parse a simple url response in PHP?

I am trying to parse a simple response from the server and use its values.

I was able to get the required information as follows:

The actual response :

AccountID=0&Authenticated=1&ResponseCode=0&ResponseText=Success

What I need is separate values for :

My code so far :

$tempValue = explode("\n", $response);

foreach($tempValue as $row => $data)          
{    
    //get row data
    $row_data = explode('&', $data);

    $row_internal = explode('=', $row_data);

    $info2[$row]['id']           = $row_internal[0];
    $info2[$row]['name']         = $row_internal[1];
    $info2[$row]['description']  = $row_internal[2];



    $info[$row]['id']           = $row_data[0];
    $info[$row]['name']         = $row_data[1];
    $info[$row]['description']  = $row_data[2];


    echo 'Account ID: ' . $info[$row]['id'] . '<br />';
    echo 'Authenticated: ' . $info[$row]['name'] . '<br />';
    echo 'Response Code: ' . $info[$row]['description'] . '<br />';
    echo '<br></br>';

    echo 'Account ID: ' . $info2[$row]['id'] . '<br />';
    echo 'Authenticated: ' . $info2[$row]['name'] . '<br />';
    echo 'Response Code: ' . $info2[$row]['description'] . '<br />';
}

Result for the above code :

Account ID: AccountID=0
Authenticated: Authenticated=1
Response Code: ResponseCode=0


Account ID: 
Authenticated: 
Response Code: 

What I needed was just the values for the fields like :

Account ID: 0
Authenticated: 1
Response Code: 0

Upvotes: 1

Views: 216

Answers (1)

Kevin
Kevin

Reputation: 41885

If this is a query string response, then no need to explode, there is a better tool that handles this well.

Just use parse_str().

Simple one line response example:

$response = 'AccountID=0&Authenticated=1&ResponseCode=0&ResponseText=Success';
parse_str($response, $data);

echo '<pre>';
print_r($data);

Or if the response looks like a multiline string like this, you could apply it like:

$response = "AccountID=1&Authenticated=1&ResponseCode=0&ResponseText=Success
AccountID=2&Authenticated=1&ResponseCode=0&ResponseText=Success
AccountID=3&Authenticated=1&ResponseCode=0&ResponseText=Success
";

$responses = explode("\n", $response);
foreach ($responses as $key => $value) {

    parse_str($value, $data);

    if(!empty($data)) {
        echo 'Account ID: '.$data['AccountID'] .'<br/>';
        echo 'Authenticated: '.$data['Authenticated'] .'<br/>';
        echo 'Response Code: '.$data['ResponseCode'] .'<br/>';
        echo 'Response Text: '.$data['ResponseText'] .'<br/>';
        echo '<br/>';
    }
}

Upvotes: 8

Related Questions