Enviar datos JSON de PHP a Node.js

En la siguiente entrada veremos como enviar datos desde PHP a un servidor Node.js. Los datos se enviarán mediante post en formato JSON y serán recogidos utilizando el framework Express.js.

PHP

  • Forma 1: haciendo uso de CURL.
        $url = 'http://localhost:4000';
        $data = array("nick" => 'CarmaZone', "twitter" => "@CarmaZone");

        $data_string = json_encode($data);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string))
        );

        $result = curl_exec($ch);
        curl_close($ch);
  • Forma 2: usando uso de PHP  (PHP 4 >= 4.3.0, PHP 5)

Sigue leyendo