Formatting JSON formatted text file in PHP - php

So I got a HTML page with a button. When I click the button, a separate javascript file sends a GET request to my PHP file, expecting a JSON object in return. My PHP reads a JSON formatted text file and should convert it into a JSONObject and echo it out for my javascipt. I had some code working before, but it doesn't seem to do it anymore since I changed to a Ajax aproach instead of having everything in the same file. This is my code:
readLog.php
<?php
class test{
function clean($string){
return json_decode(rtrim(trim($string),','),true);
}
function getLog(){
header('Content-Type: application/json');
$logLines = file('../../../home/shares/flower_hum/humid.log');
$entries = array_map("clean",$logLines);
$finalOutput = ['log' => $entries];
echo json_encode($logLines);
}
}
?>
My humid.log file looks like this:
{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }
{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }
Now If I press my button, this is the response I get checking the console in my web browser:
Response:
["{\"date\":\"26\/09\/2016\", \"time\":\"22:40:46\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }{\"date\":\"26\/09\/2016\", \"time\":\"23:10:47\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }\n"]
JSON:
"{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }\n"
obviously something is wrong with the formatting, but I don't know what. As I said, this code worked just fine when I had my php and HTML in the same file.
EDIT:
I have also tried formatting the JSON with something like this, but it just prints the brackets:
function getLog(){
$text = file('../../../home/shares/flower_hum/humid.log');
$textRemoved ="["; //Add opening bracket.
$textRemoved .= substr($text, 0, strlen($text)-1); (Remove last comma)
$textRemoved .="]";//Add closing bracket
$json = json_encode($textRemoved);
echo $json;
}

So I managed to solve it myself. Basicly The formatting of the textfile was wrong and as some commentors said, I don't need to encode it if I am doing it myself. What I ended up doing was in my application that generates the log file to add comma after each row. Then in my PHP I added brackets and removed the last comma.
function getLog(){
header('Content-Type: application/json');
$file = file_get_contents('../../../home/shares/flower_hum/humid.log');
$lengthOfFile = strlen($file)-2;
$subFile = substr($file, 0, $lengthOfFile);
$res ="[";
$res .= $subFile;
$res .="]";
echo $res;
}

You can't just jam two+ JSON strings togther. It's JSON, which means it HAS to be syntactically correct Javascript CODE. If you want to join two json strings together, you HAVE to decode them to a native data structure, join those structures together, then re-encode the new merged structure:
$temp1 = json_decode('{"foo":"bar"}', true);
$temp2 = json_decode('{"baz":"qux"}', true);
$new = array_merge($temp1, $temp2);
echo json_encode($new);
which will produce:
{"foo":"bar","baz":"qux"}
and remain valid JSON/Javascript.
Why? Consider that bare integers are valid json:
json_encode(42) -> 42
json_encode(123) -> 123
If you have two json-encoded integers and jam together, you get a "new" integer:
42123
and on the receiving end, you'll be going "Ok, so where is the split between the two", because 4 and 2123 are just as valid as possible original values as 4212 and 3.
Sending the two integers as distinct and SEPARATABLE values would require an array:
[42,123]

Related

How to extract an object within a JSON object in PHP and assign it the right index

I have the following PHP code (I'll post the important part of it):
// objID
$objects->objID = generateRandomID();
$objects->pointer = array('type'=>'__pointer','objID'=>'dgFg45dG','className'=>'Users');
$jsonStr = file_get_contents($className.'.json'); // This calls a Users.json file stored in my server
$jsonObjs = json_decode($jsonStr, true);
...
$jsonStr = file_get_contents($className.'.json'); // This calls a Users.json file stored in my server
$jsonObjs = json_decode($jsonStr, true);
array_push($jsonObjs, $objects);
// Encode the array back into a JSON string and save it.
$jsonData = json_encode($jsonObjs);
file_put_contents($className.'.json', $jsonData);
// echo JSON data
echo $jsonData;
// ISSUE HERE :(
$jsonStr = file_get_contents($className.'.json');
// Decode the JSON string into a PHP array.
$jsonObjs = json_decode($jsonStr, true);
foreach($jsonObjs as $i=>$obj) {
print_r('<br><br>'.$i.'-- ');
echo
$obj['objID'].', <br>'
.$obj['pointer']["$i"]['objID']. ', '
.$obj['pointer']["$i"]['type']. ', '
.$obj['pointer']["$i"]['className']. '<br><br>'
;
}
// ./ ISSUE
The code above creates a new JSON object into my own Users.json file.
So, when I call this PHP file with a URL string in my browser, just as a test, and I refresh the page a few times, I get the following echo:
0-- VUDjCZX8QX, , ,
1-- 1uWH17OoJP, , ,
[{"objID":"VUDjCZX8QX","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:49","updatedOn":"2018-09-17 05:36:49","number":111,"boolean":true,"array":["john","sarah"]},{"objID":"1uWH17OoJP","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:51","updatedOn":"2018-09-17 05:36:51","number":111,"boolean":true,"array":["john","sarah"]},{"objID":"RkubyQPvqR","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:54","updatedOn":"2018-09-17 05:36:54","number":111,"boolean":true,"array":["john","sarah"]}]
So, what I need to fix is basically the following:
What's the right code to properly get the list of items of the
"pointer" object that's inside each object of my Users.json file?
I try to track the index of my foreach loop, but it doesn't work properly as you can see by the echo posted above when I first execute my PHP code, I get the JSON string of my 1st object, I don't get any print_r(). Then, when I refresh the page a 2nd time, I get the print of the objID string of my 1st object, and again, if I refresh the page a 3rd time, I get the objID of my 2nd object, while there are 3 objects stored in my json file. And so on, in other words, I never get the first object's print info.
What am I doing wrong?
You are passing $i as a string, not as a variable. Use double quotes (") or remove single quotes (') to pass as a variable. This will solve your issue, pointer objects not printing properly.
$obj['pointer'][$i]['objID']
Update
[{"objID":"VUDjCZX8QX","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:49","updatedOn":"2018-09-17 05:36:49","number":111,"boolean":true,"array":["john","sarah"]},{"objID":"1uWH17OoJP","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:51","updatedOn":"2018-09-17 05:36:51","number":111,"boolean":true,"array":["john","sarah"]},{"objID":"RkubyQPvqR","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:54","updatedOn":"2018-09-17 05:36:54","number":111,"boolean":true,"array":["john","sarah"]}]
According to above JSON string, you don't need specify $i.
$obj['pointer']['objID'] should work, since it is associate array.
Thanks to #saumini-navaratnam, I have to use the following foreach:
foreach($jsonObjs as $i=>$obj) {
print_r('<br><br>'.$i.'-- ');
echo
$obj['objID'].', '
.$obj['pointer']['objID']. ', '
.$obj['pointer']['type']. ', '
.$obj['pointer']['className']. '<br><br>'
;
}
In this way, I can properly get the objects of this object:
{"pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"}
In fact, here's the echo I get:
[
{"objID":"pkO8NesS5S","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"bobby","createdOn":"2018-09-17 07:03:27","updatedOn":"2018-09-17 07:03:27","number":111,"boolean":true,"array":["john","sarah"]},
{"objID":"rdwJl20krC","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"bobby","createdOn":"2018-09-17 07:03:31","updatedOn":"2018-09-17 07:03:31","number":111,"boolean":true,"array":["john","sarah"]},
{"objID":"3WspzmuwMK","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"bobby","createdOn":"2018-09-17 07:07:39","updatedOn":"2018-09-17 07:07:39","number":111,"boolean":true,"array":["john","sarah"]}
]
0-- pkO8NesS5S, dgFg45dG, __pointer, Users
1-- rdwJl20krC, dgFg45dG, __pointer, Users
2-- 3WspzmuwMK, dgFg45dG, __pointer, Users

PHP & JSON : Trying to write JSON to Mysql

I am having an issue where my PHP script opens a file with JSON code and needs to insert it into a MySQL database.
For some reason it only displays some of the output from the JSON.
Here is my code
$json = json_decode(file_get_contents('data.json'), true);
$data = $json;
// VAR's
$system = $data['System'];
$cid_from = $data["From"];
$cid_to = $data['To'];
//DEBUG USAGES
$array = print_r($data, true);
////// THIS ONE WORKS FINE
echo $data["System"];
////// THIS ONE DOESN'T WORK
echo $data["To"];
file_put_contents('output/json-local.txt',$array . "\r\n", FILE_APPEND);
////// BUT HERE IT ACTUALLY WORKS
file_put_contents('output/cli-from.txt',$data['From']. "\r\n", FILE_APPEND);
file_put_contents('output/cli-to.txt',$data['To']. "\r\n", FILE_APPEND);
// file_put_contents('json-sysid-local.txt',$systemid . "\r\n", FILE_APPEND);
Here is the contents of data.json
{"action":"call-data-record",
"System":"48130b83e2232f0ecd366a92d4d1261d",
"PrimaryCallID":"n1bWEfCdHcf#MSS.MTN.CO.ZA-b2b_1",
"CallID":"0440b807#pbx",
"From":"<sip:+27722080036#xxx.co.za>",
"To":"<sip:27102850816#xxx.co.za>",
"Direction":"O",
"RemoteParty":"",
"LocalParty":"",
"TrunkName":"",
"TrunkID":"",
"Cost":"",
"CMC":"",
"Domain":"xxx.co.za",
"TimeStart":"2018-08-14 16:03:21",
"TimeConnected":"",
"TimeEnd":"2018-08-14 16:03:23",
"LocalTime":"2018-08-14 18:03:21",
"DurationHHMMSS":"0:00:00",
"Duration":"0",
"RecordLocation":"",
"RecordUsers":"",
"Type":"hunt",
"Extension":"100",
"ExtensionName":"100",
"IdleDuration":"",
"RingDuration":"2",
"HoldDuration":"0",
"IvrDuration":"0",
"AccountNumber":"400",
"IPAdr":"",
"Quality":"VQSessionReport: CallTerm\r\nLocalMetrics:\r\nCallID:0440b807#pbx\r\nFromID:<sip:27102850816#xxx.co.za>\r\nToID:<sip:+27722080036#xxxx.co.za>;tag=1460166964\r\nx-UserAgent:Vodia-PBX/57.0\r\nx-SIPmetrics:SVA=RG SRD=91\r\nx-SIPterm:SDC=OK SDR=OR\r\n"}
Your "To" data is encapsulated in <>. This causes your browser to interpret it as an HTML tag and not display any content.
You can (should!) escape the special HTML control characters:
echo htmlspecialchars($data["To"]);
See http://php.net/htmlspecialchars
Edit: It doesn't hurt to precautionary add this to your other outputs aswell. If the string doesn't contain such characters, it will simply be returned onchanged. You eliminate possible XSS attack vectors this way.
The browser source clearly shows "To":"" is being written by PHP to the browser output correctly but the browser is interpreting as an HTML opening tag hence ignoring the rest of the content.
Wrap your output in the PHP htmlspecialchars() function to see the output as in the file.
Add - echo "TO : ".htmlspecialchars($data["To"]);

php convert json string to array

I have a json string sent from html...
[{"user_id":"test_123"},{"id":"wallName","value":"","type":"text"},{"id":"wallLength","value":"","type":"text"}]
I want to retrieve the "user_id":"test_123" and then from that create a folder named test_123, maybe even a matching file named test_123. I'm thinking I need to convert the json file to an array, get the user_id value and convert that back to a string? Does that make sense or am I over complicating this? I'm new to php so that might very well be the case.
Here's my php code...
<?php
$json=$_POST[json];
$decodedText=html_entity_decode($json);
$myArray = json_decode($json, true);
if (json_decode($json) != null){
$file=fopen('user_data.json','w+');
fwrite($file, $json);
fclose($file);
}else{
echo "empty";
}
?>
When I try to access $myArray it doesn't work.
you can get user_id using $myArray[0]['user_id'];

Cannot Decode JSON API response

I have built an API for my shipping quote system. I feed it values and I get rate quotes back. It works fine but I cannot decode the JSON response. I get a NULL response and I'm not sure whats up. According to validaters the JSON is correct.
So what I essentially do is encode a PHP array on one side and I want to parse that on the other side using a browser and PHP. However, I get a NULL response.
Here is the JSON. Let me know if you need more.
{"carrier":"R&L Carriers","charge":"99.13","service_days":"Wednesday Oct. 22, 2014"}
I just want to decode this so I can parse it. If there is another way to parse please let me know.
Also, I searched SOF and the similar issues people were having here didn't help me.
This is the code I use to generate the JSON.
<?php
//include ('mysql_connect.php');
$result = mysql_query('select * from quote where user_id = "'.$user_id.'" order by netCharge asc limit 1');
if (!$result) {
die('Could not query:' . mysql_error());
}
if (!$result) echo mysql_error();
$api_data = array();
$api_count = '0';
while ($row = mysql_fetch_array($result, MYSQLI_ASSOC)) {
$api_data[carrier] = $row['carrier'];
$api_data[charge] = $row['netCharge'];
$api_data[service_days] = $row['serviceDays'];
$api_count++;
}
$api_data = json_encode($api_data);
print_r($api_data);
?>
This is what I'm using to grab that JSON data:
<?php
$input = file_get_contents('api_request.php?dest_zip=66101&weight=200&class=50&ltl_shipment=X&Residential_Delivery=X');
echo $input;
$obj = json_decode($input);
var_dump($obj);
?>
Have you tried the following
$array = json_decode($data, true);
Your response has an extra </div> in it.
Delete the div so that's valid JSON and the decode function will work.
http://trumrates.com/trumrates/rate/quote/signin/api_request.php?dest_zip=66101&weight=200&class=50&ltl_shipment=X&Residential_Delivery=X
Yields:
{"carrier":"R&L Carriers","charge":"99.13","service_days":"Wednesday Oct. 22, 2014"}
</div>
Summary
The built-in function json_decode (see doc) should help. According to the official document, NULL is returned if the JSON cannot be decoded or if the encoded data is deeper than the recursion limit.
I doubt the JSON string you read is actually NOT as same as PHP reads. Please make sure the string is NOT HTML escaped. And it is very important that keys and values in a JSON should be quoted by double quote. Single quote is malformed JSON, which might be considered as syntax error.
Example
To be a good demo, I put json string in file and then decode it using test.php.
In example.json:
{"carrier":"R&L Carriers","charge":"99.13","service_days":"Wednesday Oct. 22, 2014"}
In test.php:
<?php
$input = file_get_contents('example.json');
echo $input;
// {"carrier":"R&L Carriers","charge":"99.13","service_days":"Wednesday Oct. 22, 2014"}
$obj = json_decode($input);
var_dump($obj);
// object(stdClass)#1 (3) {
// ["carrier"]=>
// string(12) "R&L Carriers"
// ["charge"]=>
// string(5) "99.13"
// ["service_days"]=>
// string(23) "Wednesday Oct. 22, 2014"
// }
When I wrote the code I used 'Enter' to give me spaces between lines of code. For some reason that translated to the JSON and that's why it wasn't working. I just deleted all the extra empty lines in my file and it worked.

json encode using php not able to get [] brackets

here is my code
<?
include '../dbConnect.php';
$amp=trim($_POST['amp']);
//$amp='AMP8';
//$sql=mysql_query("select tblRepairQueue.ackNo,tblRepairQueue.repairStatus,tblRepairQueue.savedAt from tblRepairQueue,AMPcustomers where AMPcustomers.phone1=tblRepairQueue.phoneNo and AMPcustomers.id='".$amp."'");
$sql=mysql_query("select phone1 from AMPcustomers where id='".$amp."'");
$response = array();
while($row=mysql_fetch_array($sql))
{
$sql_query=mysql_query("select ackNo,repairStatus,savedAt from tblRepairQueue where phoneNo='".$row['phone1']."'");
while($row1=mysql_fetch_array($sql_query)){
$ackNo=$row1['ackNo'];
$repairStatus=$row1['repairStatus'];
$savedAt=$row1['savedAt'];
$response[]=array('ackNo'=>$ackNo,'repairStatus'=>$repairStatus,'savedAt'=>$savedAt);
}}
print json_encode($response);
?>
output m getting as
{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25",{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}
but i want the output to look like
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}]
Can anyone plz help in finding the mistake or what has to be done to get square brackets at the end
This is a bit strange because I have this code:
<?php
$array = array();
$array[] = array("ackNo"=>"26101211236759","repairStatus"=>"Closed and Complete","savedAt"=>"2012-10-26 00:55:25");
$array[] = array("ackNo"=>"26101211236780","repairStatus"=>"Closed and Complete","savedAt"=>"2012-10-26 10:55:25");
echo json_encode($array);
?>
And I get this correct form:
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"26101211236780","repairStatus":"Closed and Complete","savedAt":"2012-10-26 10:55:25"}]
This code should indeed output [{...},...]. So we can't really tell you what went wrong on your side. check the structure of the $response variable before the conversion to Json to see what went wrong.
Note that the code allows SQL injection. You must change it so that the parameters $amp and $row['phone1'] are escaped in the SQL queries. Even if you're relying on magic qoutes now, this solution is not future-proof (now-proof really) as support for this is was removed in PHP 5.4.
What you have written should work:
http://ideone.com/ErV9fr
// How many to add
$response_count=3;
// Your response, just templated
$response_template=array(
'response_number'=>0,
'ackNo'=>'dffdgd',
'repairStatus'=>'$repairStatus',
'savedAt'=>'$savedAt'
);
// Your empty response array
$response = array();
for($i=0;$i<$response_count;$i++) {
$response_template['response_number'] = $i; // Set the 'response number' to the itteration.
$response[]= $response_template; // Add the template to the collection
}
print json_encode($response);
Result:
[{"response_number":0,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"},{"response_number":1,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"},{"response_number":2,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"}]
In addition to this, you should sanitize your $amp variable. In it's current form it would be trivial for a user to escape your query and execute an arbitrary query against your DB.
http://www.php.net/manual/en/mysqli.real-escape-string.php
Please recheck it can not give you the output like that {"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25",{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}
as it is creating an array of array so it can not print like that.
It will always print like
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}]

Categories