How to properly format data as JSON - php

I am working on hotels API, which needs to send data in JSON form,
But my JSON form is wrong and the API is not working.
My code is:-
$json = json_encode([
'RoomGuests' => [ json_encode(["NoOfAdults"=> 1,"NoOfChild"=> 0,"ChildAge"=> null])],
]);
And my output is :-
{
"RoomGuests": [
"{\"NoOfAdults\":1,\"NoOfChild\":0,\"ChildAge\":null}"
] }
And I want the result like this:-
{
"RoomGuests": [{
"NoOfAdults": 1,
"NoOfChild": 0,
"ChildAge": null
}], }
Please let me know how to solve this issue.

Use this
$json = json_encode([
'RoomGuests' => [["NoOfAdults"=> 1,"NoOfChild"=> 0,"ChildAge"=> null]],
]);
echo $json;
This will results into
{
"RoomGuests": [
{
"NoOfAdults": 1,
"NoOfChild": 0,
"ChildAge": null
}
]
}

For correct output instead of:
$json = json_encode([
'RoomGuests' => [ json_encode(["NoOfAdults"=> 1,"NoOfChild"=> 0,"ChildAge"=> null])],
]);
enough to make:
$json = json_encode([
'RoomGuests' => [ ["NoOfAdults"=> 1,"NoOfChild"=> 0,"ChildAge"=> null] ],
]);
json_encode will recursively encode all sub arrays. So it is enough to call only once.

This is my code which print the output in json format.You can edit it as per yours:
<?php
include_once('connect.php');
{
error_reporting( error_reporting() & ~E_NOTICE );
$id = $_GET['id'];
$name = $_GET['name'];
$date = $_GET['date'];
$select = "select * from details";
$sel = "select id,name from details";
$res = mysqli_query($con, $select);
$result = mysqli_query($con,$sel);
while($row = mysqli_fetch_object($res))
{
$output[] = $row;
}
if(empty($output))
{
print(json_encode("User doesn't exist"));
}
else{
while($col = mysqli_fetch_object($result))
{
$output[] = $col;
}
if(empty($output))
{
print(json_encode("User doesn't exits"));
}
else{
print(json_encode($output));
}
}
}
?>

<?php
$a = (object)[
'RoomGuests' => [
(object)["NoOfAdults"=> 1,"NoOfChild"=> 0,"ChildAge"=> null]
],
];
var_export(json_encode($a));
Result:
{"RoomGuests":[{"NoOfAdults":1,"NoOfChild":0,"ChildAge":null}]}

Related

How can i do this I want to store Views in mysql db in 1000=1k, 100000=100k, 1000000=1M and so on

I have php code below i want to do this I want to store Views in mysql db in 1000=1k, 100000=100k, 1000000=1M and so on so can any one please tell me how can i do this
function updateVideoView()
{
require_once("config.php");
$input = #file_get_contents("php://input");
$event_json = json_decode($input,true);
//print_r($event_json);
if(isset($event_json['id']))
{
$id=htmlspecialchars(strip_tags($event_json['id'] , ENT_QUOTES));
mysqli_query($conn,"update videos SET view =view+1 WHERE id ='".$id."' ");
$array_out[] =
array(
"response" =>"success");
$output=array( "code" => "200", "msg" => $array_out);
print_r(json_encode($output, true));
}
else
{
$array_out = array();
$array_out[] =
array(
"response" =>"Json Parem are missing");
$output=array( "code" => "201", "msg" => $array_out);
print_r(json_encode($output, true));
}
}

Edit JSON file using PHP

I'm trying to edit a JSON file using php, I've set up a little ReactJS app has form elements.
My JSON is as follows
[
{
"id": 1,
"Client": "client 1",
"Project": "project 1",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-1"
},
{
"id": 2,
"Client": "client 2",
"Project": "project 2",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-2"
},
{
"id": 3,
"Client": "client 3",
"Project": "project 3",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-3"
}
]
So far i have code to create a new "project" at the end of the file. My PHP is as follows
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try {
$clientName = $_POST['clientName'];
$ProjectName = $_POST['projectName'];
$url = strtolower($_POST['url']);
$date = date('Y/m/d H:i:s');
$message = "";
$url = '../json/projects.json';
if( file_exists($url) )
if(file_exists('../json/projects.json'))
{
$current_data = file_get_contents('../json/projects.json');
$array_data = json_decode($current_data, true);
$extra = array(
'id' => count($array_data) + 1,
'Client' => $clientName,
'Project' => $ProjectName,
'StartDate' => $date,
'CompletedDate' => "",
'projectUrl' => $projectFileName + ".json"
);
$array_data[] = $extra;
$final_data = json_encode($array_data, JSON_PRETTY_PRINT);
if(file_put_contents('../json/projects.json', $final_data))
{
$message = "sent";
}
else
{
$message = "notSent";
}
}
else
{
$message = "jsonFileNotFound";
}
$response = $message;
} catch (Exception $e) {
$response = $e->getMessage();
}
echo $response;
}
What i can figure out is how to edit lets say "CompletedDate" value to todays date with a click of the button.
I have an hidden input field on my page that has the project ID in, so what I'm after is helping getting that id, matching it to the JSON, then editing the completed date that matches the ID.
This PHP will fire using ajax so i can pass the ID pretty easy.
Using similar code to what you already use, you can update the relevant data by using the ID as the index into the decoded JSON file. As ID 1 will be the [0] element of the array, update the [$id-1] element with the date...
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try {
$id = 2; // Fetch as appropriate
$date = date('Y/m/d H:i:s');
$url = '../json/projects.json';
if( file_exists($url) )
{
$current_data = file_get_contents($url);
$array_data = json_decode($current_data, true);
$array_data[$id-1]['CompletedDate'] = $date;
$final_data = json_encode($array_data, JSON_PRETTY_PRINT);
if(file_put_contents($url, $final_data))
{
$message = "updated";
}
else
{
$message = "notUpdated";
}
}
else
{
$message = "jsonFileNotFound";
}
$response = $message;
} catch (Exception $e) {
$response = $e->getMessage();
}
echo $response;
}
You may need to tweak some of the bits - especially how the ID is picked up ($_GET?) and any messages you want.
I've also updated the code to make more consistent use of $url as opposed to hard coding it in a few places.

I need help in json response in php

Here is my code:
<?php
while ($row = mysqli_fetch_assoc($searching_user))
{
$salon_name = ucfirst($row['service_name']);
$salon_id = ucfirst($row['id']);
$salon_address = ucwords($row['address']);
$salon_area = ucwords($row['area']);
$salon_city = ucwords($row['city']);
$salon_specialty = ucwords($row['specialty']);
$img = $row['image_url'];
$response["error"] = FALSE;
$response["service_name"] = $salon_name;
echo json_encode($response);
}
?>
after this I'm getting the response in this format
{"error":false,"service_name":"Mike
salon"}{"error":false,"service_name":"Michel salon"}
{"error":false,"service_name":"Michel salon"}{"error":false,"service_name":"Mike Salon"}
{"error":false,"service_name":"Etta Salon"}
I simply want this response like this
[ {"error":false,"service_name":"Mike
salon"},{"error":false,"service_name":"Michel
salon"},{"error":false,"service_name":"Michel
salon"},{"error":false,"service_name":"Mike Salon"},
{"error":false,"service_name":"Etta Salon"}]
Kindly help me to get a proper response form for json .
Thanks
Don't json_encode() the single results, but put them into an array and finally json_encode() that:
<?php
$response = [];
while ($row=mysqli_fetch_assoc($searching_user)) {
$salon_name = ucfirst($row['service_name']);
$salon_id = ucfirst($row['id']);
$salon_address = ucwords($row['address']);
$salon_area = ucwords($row['area']);
$salon_city = ucwords($row['city']);
$salon_specialty = ucwords($row['specialty']);
$img = $row['image_url'];
$response[] = [
'error' => FALSE,
'service_name' => $salon_name,
// you may want to add more attributes here...
];
}
echo json_encode($response);
I personally suggest to shorten this:
<?php
$response = [];
while ($row=mysqli_fetch_assoc($searching_user)) {
$response[] = [
'error' => FALSE,
'service_name' => ucfirst($row['service_name']),
'salon_id' => $row['id'],
'salon_address' => ucwords($row['address']),
'salon_area' => ucwords($row['area']),
'salon_city' => ucwords($row['city']),
'salon_specialty' => ucwords($row['specialty']),
'img' => $row['image_url'],
];
}
echo json_encode($response);
You are trying to encode single results, Try to create a array will all the results and encode it out side the loop.
while ($row=mysqli_fetch_assoc($searching_user)) {
$salon_name = ucfirst($row['service_name']);
$salon_id = ucfirst($row['id']);
$salon_address = ucwords($row['address']);
$salon_area = ucwords($row['area']);
$salon_city = ucwords($row['city']);
$salon_specialty = ucwords($row['specialty']);
$img = $row['image_url'];
$response["error"] = FALSE;
$response["service_name"]=$salon_name;
// Added this line
$responses[] = $response;
}
//Encode all results
echo json_encode($responses );

How to get json array and insert in the database. php

I have a table on an Invitation. I am passing the data in json format from postman.
I want to send many invitations at a time. So I want to insert multiple invitations.
How can I do this?
I have created a single invitation.
Invitaion :
class Invitation
{
private $sender_id,$date,$invitee_no,$status;
function Invitation($sender_id,$date,$invitee_no,$status)
{
$this->sender_id = $sender_id;
$this->date= $date;
$this->invitee_no = $invitee_no;
$this->status = $status;
}
function sendInvite()
{
$database = new Database(ContactsConstants::DBHOST,ContactsConstants::DBUSER,ContactsConstants::DBPASS,ContactsConstants::DBNAME);
$dbConnection = $database->getDB();
$stmt = $dbConnection->prepare("select * from Invitation where invitee_no =?");
$stmt->execute(array($this->invitee_no));
$rows = $stmt->rowCount();
if($rows > 0)
{
$response = array("status"=>-3,"message"=>"Invitation exists.");
return $response;
}
$stmt = $dbConnection->prepare("insert into Invitation(date,invitee_no,status) values(?,?,?)");
$stmt->execute(array($this->date, $this->invitee_no, $this->status));
$rows = $stmt->rowCount();
$Id = $dbConnection->lastInsertId();
$stmt = $dbConnection->prepare("select * from Invitation where sender_id=?");
$stmt->execute(array($Id));
$invitation = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($rows < 1) {
$response = array("status" => -1, "message" => "Failed to send Invitation., unknown reason");
return $response;
} else {
$response = array("status" => 1, "message" => "Invitation sent.", "Invitation:" => $invitation);
return $response;
}
}
}
sendInvite.php
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set('display_errors', '1');
require 'Invitation.php';
$jsonText = file_get_contents('php://input');
if(empty($jsonText))
{
$response = array("status"=>-2,"message"=>"Empty request");
die(json_encode($response));
}
$json = json_decode($jsonText);
$date= $json -> date;
$invitee_no = $json -> invitee_no;
$status = $json -> status;
$invitation = new Invitation("",$date,$invitee_no,$status);
$response = $invitation->sendInvite();
echo(json_encode($response));
?>
Input from postman:
{
"date" : "12/08/2016",
"invitee_no" : "5258",
"status" : "1"
}
Output:
{
"status": 1,
"message": "Invitation sent.",
"Invitation:": [
{
"sender_id": "29",
"date": "12/08/2016",
"invitee_no": "5259",
"status": "1"
}
]
}
EDIT:
In Send Invite() function:
if ($rows < 1) {
$response = array("status" => -1, "message" => "Failed to send Invitation., unknown reason");
echo(json_encode($response));
} else {
$response = array("status" => 1, "message" => "Invitation sent.", "Invitation:" => $invitation);
echo(json_encode($response));
}
In senInvite.php file :
foreach ($json as $jsn) {
foreach($jsn as $j)
{
$date= $j -> date;
$invitee_no = $j -> invitee_no;
$status = $j -> status;
$invitation = new Invitation("",$date,$invitee_no,$status);
$response = $invitation->sendInvite();
var_dump($response);
die();
echo(json_encode($response));
}
}
var dump:
{"status":-3,"message":"Invitation exists.","invitee_no":"5856"}array(3) {
["status"]=>
int(-3)
["message"]=>
string(18) "Invitation exists."
["invitee_no"]=>
string(4) "5856"
}
Gives syntax error: unexpeted 'S'
I want to accept this as json array and insert into the table all the records.
Can anyone help please? Thank you..
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set('display_errors', '1');
require 'Invitation.php';
$jsonText = file_get_contents('php://input');
if(empty($jsonText))
{
$response = array("status"=>-2,"message"=>"Empty request");
die(json_encode($response));
}
$response = array();
$json = json_decode($jsonText);
foreach ($json as $jsn) {
foreach($jsn as $j)
{
$date= $j -> date;
$invitee_no = $j -> invitee_no;
$status = $j -> status;
$invitation = new Invitation("",$date,$invitee_no,$status);
$response[] = $invitation->sendInvite();
}
}
echo(json_encode($response));
?>
I have used foreach for array.

Telegram Bot PHP: Warning: file_get_contents failed to open stream: 400 Bad Request

I'm editing file php for telegram bot. When I test on telegram, it shows no response at all. On PHP command line, it said:
Warning:
file_get_contents(https://api.telegram.org/bottoken/sendMessage):
failed to open
stream: HTTP request failed! HTTP/1.1 400 Bad Request in G:\xampp\htdocs\xbot\file.php on
line 39
And on line 39:
$result = file_get_contents(request_url('sendMessage'), false, $context);
But, it works when I change function create_response to this:
function create_response($text)
{
$conn = mysqli_connect("localhost","root","admintma","aq");
$data = array();
$sql = "Select s.text_sr AS surat, s.no_sr AS nosurat, qi.verseid AS ayat, " .
"qi.ayahtext AS ayattext from quranindonesia qi left join surah s on " .
"qi.suraid=s.no_sr where qi.ayahtext like '%$text%' limit 3,5";
$cari = mysqli_query($conn, $sql);
//$hasil = '';
if (mysqli_num_rows($cari) > 0) {
// output data of each row
while($row = mysqli_fetch_array($cari)) {
$hasil = "QS.[".$row["surat"]."-" . $row["nosurat"]. "]:" .
$row["ayat"]. ": " . $row["ayattext"]. ". ";
var_dump($hasil);
}
} else {
$hasil = "0 results";
}
return $hasil;
mysqli_close($conn);
}
But it only shows just last result while on php command line show complete result:
string(157) "Value1"
string(219) "Value2"
string(462) "Value3"
string(555) "Value4"
string(246) "Value5"
{
"ok": true,
"result": {
"message_id": 197,
"from": {
"id": 107653xxx,
"first_name": "x_bot",
"username": "x_bot"
},
"chat": {
"id": 2887198,
"first_name": "xxx",
"username": "xxx"
},
"date": 1437240345,
"reply_to_message": {
"message_id": 196,
"from": {
"id": 2887xxx,
"first_name": "xxx",
"username": "xxx"
},
"chat": {
"id": 2887xxx,
"first_name": "xxx",
"username": "xxx"
},
"date": 1437240342,
"text": "mengetahuinya"
},
"text": "Value5"
}
}
I'm confused, how to solve this problem? Thanks in advance.
Here's the complete code:
<?php
include("token.php");
//include("db.php");
function request_url($method)
{
global $TOKEN;
return "https://api.telegram.org/bot" . $TOKEN . "/". $method;
}
function get_updates($offset)
{
$url = request_url("getUpdates")."?offset=".$offset;
$resp = file_get_contents($url);
$result = json_decode($resp, true);
if ($result["ok"]==1)
return $result["result"];
return array();
}
function send_reply($chatid, $msgid, $text)
{
$data = array(
'chat_id' => $chatid,
'text' => $text,
'reply_to_message_id' => $msgid
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents(request_url('sendMessage'), false, $context);
print_r($result);
}
function create_response($text)
{
$conn = mysqli_connect("localhost","root","xxx","aq");
$data = array();
$sql = "Select s.text_sr AS surat, s.no_sr AS nosurat, qi.verseid AS ayat, " .
"qi.ayahtext AS ayattext from quranindonesia qi left join surah s on " .
"qi.suraid=s.no_sr where qi.ayahtext like '%$text%' limit 3,5";
$cari = mysqli_query($conn, $sql);
//$hasil = '';
if (mysqli_num_rows($cari) > 0) {
$hasil = array();
// output data of each row
while($row = mysqli_fetch_array($cari)) {
$hasil[] = "QS.[".$row["surat"]."-" . $row["nosurat"]. "]:" .
$row["ayat"] . ": " . $row["ayattext"] . ". ";
//var_dump($hasil);
}
} else {
$hasil = "0 results";
}
return $hasil;
mysqli_close($conn);
}
function process_message($message)
{
$updateid = $message["update_id"];
$message_data = $message["message"];
if (isset($message_data["text"])) {
$chatid = $message_data["chat"]["id"];
$message_id = $message_data["message_id"];
$text = $message_data["text"];
$response = create_response($text);
send_reply($chatid, $message_id, $response);
}
return $updateid;
}
function process_one()
{
$update_id = 0;
if (file_exists("last_update_id")) {
$update_id = (int)file_get_contents("last_update_id");
}
$updates = get_updates($update_id);
foreach ($updates as $message)
{
$update_id = process_message($message);
}
file_put_contents("last_update_id", $update_id + 1);
}
while (true) {
process_one();
}
?>
The problem is that your function process_message() expects create_response() to return a string, and the code that doesn't work is returning an array when there are results and a string when there are no results. It's best if it returns always the same type of data.
To fix it, change the create_response() function to always return an array, and have process_message() to use it however it needs, i.e., transform it in a string.
By the way, your return command must be the last command executed in the function. You have mysqli_close($conn); after it, which is never executed if return is above it.
So, those two functions become:
function create_response($text)
{
$conn = mysqli_connect("localhost","root","xxx","aq");
$data = array();
$sql = "Select s.text_sr AS surat, s.no_sr AS nosurat, qi.verseid AS ayat, " .
"qi.ayahtext AS ayattext from quranindonesia qi left join surah s on " .
"qi.suraid=s.no_sr where qi.ayahtext like '%$text%' limit 3,5";
$cari = mysqli_query($conn, $sql);
$hasil = array();
if (mysqli_num_rows($cari) > 0) {
// output data of each row
while($row = mysqli_fetch_array($cari)) {
$hasil[] = "QS.[".$row["surat"]."-" . $row["nosurat"]. "]:" .
$row["ayat"] . ": " . $row["ayattext"] . ". ";
}
}
mysqli_close($conn);
return $hasil;
}
function process_message($message)
{
$updateid = $message["update_id"];
$message_data = $message["message"];
if (isset($message_data["text"])) {
$chatid = $message_data["chat"]["id"];
$message_id = $message_data["message_id"];
$text = $message_data["text"];
$responseArr = create_response($text);
if (count($responseArr) > 0) {
$response = implode(". ", $responseArr) . ".";
} else {
$response = "0 results";
}
send_reply($chatid, $message_id, $response);
}
return $updateid;
}

Categories