Home > other >  Need to pass dynamic values inside CURLOPT_POSTFIELDS
Need to pass dynamic values inside CURLOPT_POSTFIELDS

Time:10-26

I have to make a post request and have done the same using postman for testing. Now, the code base is using php and I have never used php ever before. Upon checking the code section in postman, I got this:

CURLOPT_POSTFIELDS =>'{"datalist":[{
    "Firstname":"firstname",
    "Lastname":"lastname4",
    "Email":"[email protected]",
    "Phone":"9899999999",
    "leadsource":"Website",
    "address":"lakeview",
    "pincode":"440010",
    "Grade":"Class 1",
    "utmcampaign":"summer_sale",
    "utmcontent":"video_ad",
    "utmmedium":"organic_social",
    "utmterm":"social_media",
}
]}'

The problem is that I have to pass dynamic values instead of firstname, lastname4 etc. The values I have are stored as such $lead['name'].

So, basically I have to pass $lead['name'] instead of lastname4 but I am not able to figure out the syntax.

CodePudding user response:

You can use json_encode on an array to build the desired JSON string

$arr=array(
    'datalist'=>array( array(
        'Firstname'=>$lead['name'],
        'Lastname'=>$lead['last'],
        'Email'=>$lead['email'],
        'Phone'=>$lead['phone'],
        'leadsource'=>$lead['website'],
        
        /*... etc */
    )
) );

CURLOPT_POSTFIELDS=json_encode( $arr );
  • Related