Call a json web service from PHP and read back the results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | <?php // build the json request $userid = 'jonest'; //strip invalid characters that would not encode to json $userid = str_replace(':','',$userid); $userid = str_replace(',','',$userid); $userid = str_replace('"','',$userid); $userid = str_replace('{','',$userid); $userid = str_replace('}','',$userid); // create an array and encode to json $data = array("userid" => $userid, "password" => "secret"); $data_string = json_encode($data); // send the request to the json web service $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://itsmetor.com/test.json'); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)) ); // get the results back $result = curl_exec($ch); curl_close($ch); if(json_decode($result) == NULL) { echo("Not a valid json return string!"); }else { $json = json_decode($result); if ($json->{'code'} == "0") { // if the code is valid, continue searching if (isset($json->{'attribute_one'})) { echo "Found: " . $json->{'attribute_one'}; } } else { echo "Error code returned: " . $json->{'code'}; } } ?> |