index.php?id=115

Enviar y recibir datos JSON mediante PHP cURL

Por Yal Publicidad


Publicado el Mar 10 de Enero del 2023 a las 22:22



En este tutorial veremos como enviar y recibir datos JSON mediante PHP cURL.

En el siguiente ejemplo realizaremos un solicitud POST y enviaremos los datos JSON a una URL con cURL en PHP.

enviarjson.php

//API URL
$url = 'http://www.example.com/api';

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

//setup request to send json via POST
$data = array(
    'username' => 'codexworld',
    'password' => '123456'
);
$payload = json_encode(array("user" => $data));

//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'));

//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);

recibirjson.php

$data = json_decode(file_get_contents('php://input'), true);

Fuente: codexworld.com


Deja un comentario:
Buscar
Acerca de Nosotros
@yalpublicidad Agencia de publicidad online. 21 años de experiencia en el diseño y desarrollo de imagen e identidad corporativa de tu empresa...