Issue
I have this JSON data:
{
userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
itemKind: 0,
value: 1,
description: 'Saude',
itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}
and I need to post to JSON URL: http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount
How can I send this POST request using PHP?
Solution
Without using any external dependency or library:
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
$response
is an object. Properties can be accessed as usual, e.g. $response->...
where $data
is the array containing your data:
$data = array(
'userID' => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
'itemKind' => 0,
'value' => 1,
'description' => 'Boa saudaƄo.',
'itemID' => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);
Warning: this won't work if the allow_url_fopen
setting is set to Off
in the php.ini file.
If you're developing for WordPress, consider using the provided APIs: https://developer.wordpress.org/plugins/http-api/
Answered By - David Riccitelli Answer Checked By - Candace Johnson (WPSolving Volunteer)