Home > front end >  How to use a "curl -X POST" command with query in PHP?
How to use a "curl -X POST" command with query in PHP?

Time:01-15

I want to use the command below:

curl -X POST 'https://graphcdn.frankenergie.nl/' -H 'Content-Type: application/json' -H 'User-Agent: Integromat/production' -d '{
"query": "query MarketPrices {\n\tmarketPricesElectricity(startDate: \"2023-01-12\", endDate: \"2023-01-15\") {\n till\n from\n marketPrice\n priceIncludingMarkup\n\t}\n\tmarketPricesGas(startDate: \"2023-01-11\", endDate: \"2023-01-11\") {\n from\n till\n marketPrice\n priceIncludingMarkup\n }\n}"
}'

When I execute this command in the command line it works fine (result

Now I try to use the same command in a PHP script but I get error: PHP Parse error: syntax error, unexpected identifier "curl_setopt" in /home/scripts/test.php on line 11

The script I tried is:

<?php
// API URL
$url = 'https://graphcdn.frankenergie.nl/';

// Create a new cURL resource
$ch = curl_init($url);

$payload = '{"query": "query MarketPrices {\n\tmarketPricesElectricity(startDate: \"2023-01-12\", endDate: \"2023-01-15\") {\n till\n from\n marketPrice\n priceIncludingMarkup\n\t}\n\tmarketPricesGas(startDate: \"2022-06-09\", endDate: \"2022-06-10\") {\n from\n till\n marketPrice\n priceIncludingMarkup\n }\n}"}'

// Attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

// Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'User-Agent: Integromat/production'));

// Return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the POST request
$result = curl_exec($ch);

// Close cURL resource
curl_close($ch);
?>

CodePudding user response:

It has happened to all of us, but that error says that you're missing a semi-colon at the end of payload.

Shortest answer I've ever written:

Change:

$payload = '{"query": "query MarketPrices {\n\tmarketPricesElectricity(startDate: \"2023-01-12\", endDate: \"2023-01-15\") {\n till\n from\n marketPrice\n priceIncludingMarkup\n\t}\n\tmarketPricesGas(startDate: \"2022-06-09\", endDate: \"2022-06-10\") {\n from\n till\n marketPrice\n priceIncludingMarkup\n }\n}"}'

to

$payload = '{"query": "query MarketPrices {\n\tmarketPricesElectricity(startDate: \"2023-01-12\", endDate: \"2023-01-15\") {\n till\n from\n marketPrice\n priceIncludingMarkup\n\t}\n\tmarketPricesGas(startDate: \"2022-06-09\", endDate: \"2022-06-10\") {\n from\n till\n marketPrice\n priceIncludingMarkup\n }\n}"}';
  • Related