What is the best way to parse Paypal NVP in PHP?

Posted by xsaero00 on Stack Overflow See other posts from Stack Overflow or by xsaero00
Published on 2010-03-25T23:20:17Z Indexed on 2010/03/25 23:23 UTC
Read the original article Hit count: 433

Filed under:
|

I need a function that will correctly parse NVP into PHP array. I have been using code provided by paypal but it did not work for when string length was specified next to the name.

Here is what i have so far.

private function parseNVP($nvpstr)
{
    $intial=0;
    $nvpArray = array();

    while(strlen($nvpstr))
    {
        //postion of Key
        $keypos= strpos($nvpstr,'=');
        //position of value
        $valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);

        /*getting the Key and Value values and storing in a Associative Array*/
        $keyval=substr($nvpstr,$intial,$keypos);
        $vallength=$valuepos-$keypos-1;
        // check if the length is explicitly specified
        if($braketpos = strpos($keyval,'['))
        {
            // override value length
            $vallength = substr($keyval,$braketpos+1,strlen($keyval)-$braketpos-2);
            // get rid of brackets from key name
            $keyval = substr($keyval,0,$braketpos);
        }
        $valval=substr($nvpstr,$keypos+1,$vallength);
        //decoding the respose
        if (isValidXMLString("<".urldecode($keyval).">".urldecode( $valval)."</".urldecode($keyval).">"))
            $nvpArray[urldecode($keyval)] =urldecode( $valval);
        $nvpstr=substr($nvpstr,$keypos+$vallength+2,strlen($nvpstr));
     }
    return $nvpArray;
}

This function works most of the time.

© Stack Overflow or respective owner

Related posts about php

Related posts about paypal-nvp