This is a question and answer after much research using some info from other responses found on stackoverflow.
How do I convert command-line curl to php:
$ curl -X POST "https://api.cloudflare.com/client/v4/zones/023e105f4ecef8ad9ca31a8372d0c353/dns_records" \
-H "X-Auth-Email: [email protected]" \
-H "X-Auth-Key: c2547eb745079dac9320b638f5e225cf483cc5cfdda41" \
-H "Content-Type: application/json" \
--data '{"type":"A","name":"example.com","content":"127.0.0.1","ttl":120}'
The above curl is an example from cloudflare's api manual on how to add an A record. I needed to add numerous CNAMES or subdomains. Cloudflare does not explain how to modify the above code to create CNAMES. So I will get that out of the way first:
$ curl -X POST "https://api.cloudflare.com/client/v4/zones/023e105f4ecef8ad9ca31a8372d0c353/dns_records" \
-H "X-Auth-Email: [email protected]" \
-H "X-Auth-Key: c2547eb745079dac9320b638f5e225cf483cc5cfdda41" \
-H "Content-Type: application/json" \
--data '{"type":"CNAME","name":"subdomain.example.com","content":"example.com","ttl":120}'
First I changed "type" field to "CNAME". Next the "name" field is where you put the subdomain / CNAME or in my case the resulting variable from a foreach. Finally under the "content" field you put the domain your new CNAME points to.
What this looks like in php:
$ch = curl_init();
$headers = array(
'X-Auth-Email: [email protected]',
'X-Auth-Key: c2547eb745079dac9320b638f5e225cf483cc5cfdda41',
'Content-Type: application/json',
);
$data = array(
'type' => 'CNAME',
'name' => 'subdomain.example.com',
'content' => 'example.com',
'ttl' => '120',
);
$json = json_encode($data);
curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones/023e105f4ecef8ad9ca31a8372d0c353/dns_records");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_exec($ch);
curl_close($ch);
The other answers left out the need for "json_encode". Hope this helps.