Skip to content
Advertisement

Need to pass dynamic values inside CURLOPT_POSTFIELDS

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":"lead@test2.com",
    "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.

Advertisement

Answer

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 );
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement