JasonS JasonS - 1 year ago 68
PHP Question

PHP, How to POST a file content as json?

I have this php code, and it works, but the contents of

are being posted as a string encapsulating the file contents.

I want it to be posted the file contents directly (a text file containing json). How do I need to change this code so that
not being re-encapsulated as a string before sending?

I am guessing my
'content' => json_encode( $payload )
line needs to change, but do not know PHP enough to know how to change it.

$url = 'http://api.phantomjscloud.com/examples/helpers/requestdata';
$payload = file_get_contents ( 'request.json' );

$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n",
'method' => 'POST',
'content' => json_encode( $payload )
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }


PS: I don't want to use 3rd party libraries like curl or zend. Just Php!

EDIT 1: clarification for those complaining json is just text.


when trying either
'content' => json_decode( $payload )

I get the error:

Warning: file_get_contents(http://api.phantomjscloud.com/examples/helpers/requestdata): failed to open stream: HTTP request failed! HTTP/1.0 411 Length Required
in request.php on line 15

my request.json contents are simple, if that matters:



@Nasreddine answer is right.
file wasn't actually correct json (i didn't encapsulate the keys in double-quotes) so I was getting a http-response error for bad json posted.

thank you, my bad :(

Answer Source

You're re-encoding what is already json as a json text. So instead of this:

'content' => json_encode( $payload )

Use this:

'content' => $payload