I am working with Facebook’s API, and I’m trying to conduct a cURL request in PHP.
This request is a POST request and passes some JSON data.
I want this JSON data to be an array within PHP, then pass this into the cURL request.
Here is an example cURL request from FB’s documentation.
curl -X POST
-F 'data=[
{
"event_name": "PageView",
"event_time": 1610378833,
"user_data": {
"fbc": "fb.1.1554763741205.AbCdEfGhIjKlMnOpQrStUvWxYz1234567890",
"fbp": "fb.1.1558571054389.1098115397",
"em": "309a0a5c3e211326ae75ca18196d301a9bdbd1a882a4d2569511033da23f0abd"
}
}
]'
-F 'access_token=<ACCESS_TOKEN>'
https://graph.facebook.com/v9.0/<PIXEL_ID>/events
I have tried multiple attempts in PHP, but my array doesn’t seem to be parsed correctly.
Here is my PHP Code:
$data = array("data" => array("event_name" => "Purchase", "event_time" => time()),
"access_token" => "EAADZAQ7wNP3UBAMjOcHJV1dvgRYPoyarnLPO5Rr6cwRiOuF0biRTZCJWbCn000U9SD8hovXoKZB0zg1H8PoTI3d4RuvUZC1VQshieXSPcZABiCwqi1rgzzaYZBfMkD6qgAZBKikCtG3jO9SYWanuPUvctypbyoxQm4zVI5Cq8K"
);
$dataString = json_encode($data);
$ch = curl_init('https://graph.facebook.com/v9.0/229975271636842/events');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($dataString))
);
echo $result = curl_exec($ch);
Here is the error:
{"error":{"message":"(#100) param data must be an array.","type":"OAuthException","code":100,"fbtrace_id":"ACWsWbLVtlLZdbMyty_9VKA"}}
Here is Facebook’s Documentation.
I would appreciate any help. Thank you.
3
Answers
As the error says, you don’t need to json_encode the data.
and then pass it to your curl function.
For Nico. Right. I forgort explanation: I think:
means Object inside array. And the FB Error Response tell us: "error":{"message":"(#100) param data must be an array. And Jack encode the whole data to a datastring.
I think that the problem is that an array is missing. The "data" field is an array with an object inside.
Try this: