JasonS
JasonS

Reputation: 7733

PHP, How to POST a file content as json?

I have this php code, and it works, but the contents of request.json 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 $payload 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 */ }

var_dump($result);

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.

EDIT 2:

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
bool(false)

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

{
    "hi":"world"
}

EDIT 3:

@Nasreddine answer is right. my request.json 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 :(

Upvotes: 1

Views: 7687

Answers (2)

nospor
nospor

Reputation: 4220

Try this:

'content' => $payload

Eventually this:

'content' => json_decode( $payload )

Upvotes: 1

Nasreddine
Nasreddine

Reputation: 37838

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

'content' => json_encode( $payload )

Use this:

'content' => $payload

Upvotes: 4

Related Questions