-2

I have this curl code i need to convert it to php

curl -H "Content-Type: application/json" -d '{"command":"sendoffer", 
"steamID":"###############","token":"lkTR4VG2", "itemIDsToRequest":["4942877123","4892501549"],
"message": "Message"}' http://website:1337/

As you can see there is an array along with normal json.

"itemIDsToRequest":["4942877123","4892501549"]

I looked at many question like this and this, but couldn't understand how to implement it.

Im sorry im very new to curl command.

Community
  • 1
  • 1
SkyPunch
  • 313
  • 1
  • 4
  • 19

2 Answers2

2

the array is part of a JSON string that is not interpreted but used as plain string data in CURL so it does not really matter what is in there; use the very same JSON string as from your commandline example, so:

$data = '{"command":"sendoffer", "steamID":"###############","token":"lkTR4VG2", "itemIDsToRequest":["4942877123","4892501549"], "message": "Message"}'
curl_setopt($ch, CURLOPT_POSTFIELDS, $data );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
Hans Z.
  • 50,496
  • 12
  • 102
  • 115
  • Yes he's right. No need to convert to a php array :D Why did i do it ?! – Adam Cherti Dec 21 '14 at 09:40
  • I answered the question strictly, but I'm sure the json_encode call is something that would part of the answer to his next question ;-) – Hans Z. Dec 21 '14 at 09:47
  • @HansZandbelt im creating array dynamically .. so instead of creating array should i just create a string in that format – SkyPunch Dec 21 '14 at 10:03
  • 1
    well if you have to assemble data dynamically, direct string manipulation is often more painful and error prone than managing an array and finally calling `json_encode` when you're ready to send it; just consider the string manipulation that you would have to do if you wanted to add a single item to your existing `$data` as opposed to adding it to an array – Hans Z. Dec 21 '14 at 11:30
0

If your array is

$data = array("command"=>"sendoffer", "steamID"=>"###############","token"=>"lkTR4VG2", "itemIDsToRequest"=>array("4942877123","4892501549"),"message"=>"Message");

Then send it on its way as json format with curl like that :

$url = 'http://website:1337/';
$ch = curl_init( $url );

// Convert array to json string
$data_json = json_encode( $data );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $data_json );

// Indicate in the header that it is json data
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); 

// Send request
$result = curl_exec($ch);
curl_close($ch);
Adam Cherti
  • 962
  • 1
  • 8
  • 21