Array turn to json using php - php

need your help on this one...
I'm trying to create a code that will get a .txt file and convert all text content to json.
here's my sample code:
<?php
// make your required checks
$fp = 'SampleMessage01.txt';
// get the contents of file in array
$conents_arr = file($fp, FILE_IGNORE_NEW_LINES);
foreach($conents_arr as $key=>$value)
{
$conents_arr[$key] = rtrim($value, "\r");
}
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
echo $json_contents;
?>
I already got the result when i tried to echo the $json_contents
["Sample Material 1","tRAINING|ENDING","01/25/2018 9:37:00 AM","639176882315,639176882859","Y,Y","~"]
but when I tried to echo using like this method $json_contents[0]
I only got per character result.
Code
Result
hope you can help me on this one..
thank you

As PHP.net says
"Returns a string containing the JSON representation of the supplied value."
As you are using $json_contents[0] this will return the first char of the json string.
You can do this
$conents_arr[0]
Or convert your json string to PHP array using
$json_array = json_decode($json_contents, true);
echo $json_array[0];

It is happening because $json_contents is a string. It might be json string but it's string so string properties will apply here and hence when you echo $json_contents[0] it gives you first character of the string. You can either decode the encoded json string to object like below:
$json = json_decode($json_contents);
echo $json[0];
or echo it before the json_encode:
echo $conents_arr[0];
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);

json_encode() function takes an array as input and convert it to json string.
echo $json_contents; just print out the string.
if you want to access it you have to decode the JSON string to array.
//this convert array to json string
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
//this convert json string to an array.
$json_contents = json_decode($json_contents, true);
//now you can access it
echo $json_contents[0];

Related

How to replace string from getting postman as parameter

Currently i am facing issue of replace string , I used postman & passing string in postman like [{"id":"115","flag":"1","qty":"3","size":"10"}] as a parameters but when i print string i am getting output like [{\"id\":\"115\",\"flag\":\"1\",\"qty\":\"3\",\"size\":\"10\"}] , So i want to only remove '\' from string i have tried following code but not work.
$fliesid_in_store = $_REQUEST['fliesid_in_store'];
echo $res = preg_replace("/[^a-zA-Z]/", "", $fliesid_in_store);
Have you tried stripslashes.
$fliesid_in_store = $_REQUEST['fliesid_in_store'];
echo stripslashes($fliesid_in_store);
The string you mentioned is in json format
$json = [{"id":"115","flag":"1","qty":"3","size":"10"}] //this is json
Assign that to variable and decode it.
$string = json_decode($json,TRUE) this give result in array format
In your case
$string = json_decode($_REQUEST['fliesid_in_store'],TRUE);

Can't decode JSON from file in PHP

I'm having troubles with json_decode in PHP:
I have this on file:
{1: ['oi','oi'], 2: ['foo','bar']}
And this is my php code:
<?php
$string = file_get_contents("quizen.json"); // the file
$json = json_decode($string);
echo $json[1][0]
?>
But the echo returns anything, I used var_dump, and I get NULL!
What's the problem?
The issue is that your file is not valid JSON since it uses single quotes for strings and has integers as object keys:
{1: ['oi','oi'], 2: ['foo','bar']}
Also, since the JSON is an object, you should decode it to an associative array using json_decode($string, true).
According to the JSON spec:
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array.
Also, the object keys need to be strings.
If you change the single quotes to double quotes and edit your PHP's decode_json call to decode to an associative array, it should work. For example:
JSON:
{"1": ["oi","oi"], "2": ["foo","bar"]}
PHP:
<?php
$string = file_get_contents("quizen.json"); // the file
$json = json_decode($string, true); // set to true for associative array
echo $json["1"][0];
?>

PHP Serialize($array) without dumping array info a:1:{i:0;s:4.... and so on

Is there anything that i print the string without the array information?
(Without this: a:1:{i:0;s:4011:" ";} )?
The whole array must be in single variable and printed. Foreach doesn't help, neither print(array[0]).
You can use json_encode() which will give you less verbose string representation:
<?php
$a = array('a', 'bb' => 'ccc');
echo json_encode($a);
// outputs {"0":"a","bb":"ccc"}
You can use
echo json_encode($array);
This will print a json encoded string.
For you to decode it you can use
json_decode(json encoded string);
You can see docs of php about json encode and json decode

Base64 Decode in php with a json_decode

Hi i have the following issue where in some instances the json_decode does not work and i get an empty array as follows.
// for test purpose set the inbound enc parameter
$_POST["enc"] = "eyJ0cmFuc2NyaXB0IjoiLSAgICAgICAgICBQYXN0ZWQgdGhlIHRleHQgaW50byBOb3RlcGFkIBMgbm8gc3BlY2lhbCBjaGFyYWN0ZXJzIiwiaWQiOjcwLCJpc0FjdGlvbmVkIjp0cnVlLCJ1c2VyX2lkIjoxLCJ0YXNrX3R5cGVfaWQiOjEsImFjY291bnRfaWQiOjIxLCJhY2NvdW50X25hbWUiOiJURVNUIiwiZXZlbnRfZGF0ZSI6bnVsbH0=";
$decoded = base64_decode($_POST["enc"]);
$ar = (array)json_decode($decoded);
echo "<pre>";
print_r($decoded);
echo "</pre>";
echo "<pre>";
print_r($ar);
echo "</pre>";
$decoded displays as a json string, but $ar is null.
Any help please will be appreciated in helping me with this issue.
You didn't supply the second parameter in json_decode to return as an array, and not an object
// for test purpose set the inbound enc parameter
$_POST["enc"] = "eyJ0cmFuc2NyaXB0IjoiLSAgICAgICAgICBQYXN0ZWQgdGhlIHRleHQgaW50byBOb3RlcGFkIBMgbm8gc3BlY2lhbCBjaGFyYWN0ZXJzIiwiaWQiOjcwLCJpc0FjdGlvbmVkIjp0cnVlLCJ1c2VyX2lkIjoxLCJ0YXNrX3R5cGVfaWQiOjEsImFjY291bnRfaWQiOjIxLCJhY2NvdW50X25hbWUiOiJURVNUIiwiZXZlbnRfZGF0ZSI6bnVsbH0=";
$decoded = base64_decode($_POST["enc"]);
$ar = json_decode($decoded, true); //<-- Now returned as an array, and not an object
echo "<pre>";
print_r($decoded);
echo "</pre>";
echo "<pre>";
print_r($ar);
echo "</pre>";
Output
{"transcript":"- Pasted the text into Notepad no special characters","id":70,"isActioned":true,"user_id":1,"task_type_id":1,"account_id":21,"account_name":"TEST","event_date":null}
The error is in your JSON - oddly in the two spaces between "Notepad" and "no".
It looks like there's a nonstandard character between the spaces. Remove that character and the JSON is valid.
Invalid
{"transcript":"- Pasted the text into Notepad no special characters","id":70,"isActioned":true,"user_id":1,"task_type_id":1,"account_id":21,"account_name":"TEST","event_date":null}
Valid
{"transcript":"- Pasted the text into Notepad no special characters","id":70,"isActioned":true,"user_id":1,"task_type_id":1,"account_id":21,"account_name":"TEST","event_date":null}
In the future, ideally you would use json_encode to build your JSON string. The function will automatically escape any non-valid characters for you.
Taking your code and decoding the Base64 encoded string it turns out you have a CHR(13) ASCII character in your JSON data which is causing the JSON to fail validation according to JSON Lint. Taking that character out results in the JSON parsing correctly.
PHP Fiddle
Decoded JSON data:
{
"transcript": "- Pasted the text into Notepad no special characters",
"id": 70,
"isActioned": true,
"user_id": 1,
"task_type_id": 1,
"account_id": 21,
"account_name": "TEST",
"event_date": null
}
HEX Editor Screenshot:

counting the number of arrays in a php decoded string

I have two json decoded strings:
{"Coords":[{"Accuracy":"66","Latitude":"88","Longitude":"99","Timestamp":"100"}]}
and I have another string
{"Coords":[{"Accuracy":"222","Latitude":"333","Longitude":"444","Timestamp":"2013"},{"Accuracy":"3434","Latitude":"565","Longitude":"676","Timestamp":"7878"}]}.
Is there a way to be able to echo that the first string has 1 array and the second string has 2? My method was as following:
$Json_String=($_POST['Json']); $Json_Decoded= json_decode($Json_String, true); echo count(json_decode($Json_String, true));
where $Json_String is just what I'm pasting into a text field for now for testing purposes.
Do,
json_decode($jsonString, true);
for each string that will return you array. You can then count the length of array easily.
if you just want to kown the length try this:
echo substr_count (' {"Coords":[{"Accuracy":"222","Latitude":"333","Longitude":"444","Timestamp":"2013"},{"Accuracy":"3434","Latitude":"565","Longitude":"676","Timestamp":"7878"}]}.','Accuracy');

Categories