Search code examples
phparraysurl-encoding

Ampersands in a URL are converted to "amp;" when converting to an array in PHP


I'm using a PHP function called parse_str to convert some URL-encoded data (like "name=blah&number=123") to a PHP array. It does work correctly, but it puts an "amp;" at the beginning of each key in the resulting associative array, except the first key. For example:

response=Fail&responsecode=1&description=DUPLICATE_TRANSACTION

is converted to the following array:

Array ( [ \"1.0\" 
encoding=\"utf-8\"?>
response=Fail 
[amp;responsecode] => 1 
[amp;description] => DUPLICATE_TRANSACTION)

using the following code:

parse_str($response, $response_array);
print_r($response_array);

I'm not sure why it's adding those "amp;"s. What's the problem here?


Solution

  • I cannot reproduce it:

    <?php
    
    $response = 'response=Fail&responsecode=1&description=DUPLICATE_TRANSACTION';
    parse_str($response, $response_array);
    print_r($response_array);
    
    Array
    (
        [response] => Fail
        [responsecode] => 1
        [description] => DUPLICATE_TRANSACTION
    )
    

    However, you provide a useful hint in one of your comments:

    string(614) " response=Fail&responsecode=1&description=DUPLICATE_TRANSACTION"
    

    That's obviously not a 614 byte string. Your data is not response=Fail&responsecode=1&description=DUPLICATE_TRANSACTION.

    That, and the fact that you're getting this:

    [ \"1.0\" 
    encoding=\"utf-8\"?>
    

    ... suggests that you actually have an XML or HTML document, but you are letting the browser render it as HTML, thus the tags are hidden. Please use your browser's "View Source" feature (typically Ctrl+U) to see the real input.