Php Json code (Send joson to service rest)

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Techbboy992
Forum Newbie
Posts: 2
Joined: Fri Dec 12, 2014 2:23 pm

Php Json code (Send joson to service rest)

Post by Techbboy992 »

Hi there

I try make a user via a rest service with json data

A working code for login in same rest is:

Code: Select all

$user= $_GET["user"];
$password= $_GET["pw"];

$fields = array(
    "operatorId" => "1",
    "userName" => "$user",
    'password' => "$password");

	
	
	$json_data = json_encode($fields);
 
$post = file_get_contents('https://server:9090/user-service-rest/rest/users/',null,stream_context_create(array(
    'http' => array(
        'protocol_version' => 1.1,
        'user_agent'       => 'PHPExample',
        'method'           => 'POST',
        'header'           => "Content-type: application/json\r\n".
                              "Connection: close\r\n" .
                              "Content-length: " . strlen($json_data) . "\r\n",
        'content'          => $json_data,
    ),
)));
To register I nedd parse a little different json string, that coursing me problems:
The documentation shows following to create a user:

Code: Select all

{
  "password" : "pwd",
  "user" : {
    "userName" : "RaoulDuke",
    "operatorId" : "1",
    "userInformation" : {
      "billingAddress" : "Kungsgatan 1",
      "city" : "Stockholm",
      "country" : "Sweden"
    }
  }
}
How can I build this in existing script ?

Regards
Brian Olsen
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Php Json code (Send joson to service rest)

Post by requinix »

Get the data into the right form in PHP (that is, with arrays) then json_encode() it. The PHP array equivalent to that sample JSON is

Code: Select all

array(
	"password" => "pwd",
	"user" => array(
		"userName" => "RaoulDuke",
		"operatorId" => "1",
		"userInformation" => array(
			"billingAddress" => "Kungsgatan 1",
			"city" => "Stocklholm",
			"country" => "Sweden"
		)
	)
)
Techbboy992
Forum Newbie
Posts: 2
Joined: Fri Dec 12, 2014 2:23 pm

Re: Php Json code (Send joson to service rest)

Post by Techbboy992 »

Thank You very much it solved my problem

Regards
Brian Olsen
Post Reply