Last active
April 19, 2018 14:19
-
-
Save gregmercer/b1f1a364f433225c7502f781c9f6400d to your computer and use it in GitHub Desktop.
curl POST using php - with json data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$endpoint = "<the endpoint url for the post>"; | |
function doPost($endpoint) { | |
$items = array( | |
'postitem1' => 'abc', | |
'postitem2' => 'def', | |
); | |
$post_data = json_encode($items); | |
//open connection | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $endpoint); | |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_POST, true); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); | |
curl_setopt($ch, CURLOPT_HEADER, true); | |
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json')); | |
//curl_setopt($ch, CURLOPT_VERBOSE, true); | |
//execute post | |
$result = curl_exec($ch); | |
$pos = strpos($result, '{'); | |
$json = substr($result, $pos); | |
$data = json_decode($json); | |
if (!empty($data->results["0"])) { | |
$something = $data->results["0"]->something; | |
} | |
//close connection | |
curl_close($ch); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment