I found that many of you use a function like this...
function isJson($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
(from Fastest way to check if a string is JSON in PHP?)
Many of json encoded string contain these characters { : , "
If i check the string that contain these characters it may return true.
example:
$var = '{"1":"a2","a2":{"1":"a2.2","2":"a2.2"}}';
var_dump(isJson($var)) // true;
But when i check the string that is just a number, it return true too.
example:
$phone = '021234567';
var_dump(isJson($phone)); // true
I don't think the string '021234567' is json encoded and it should return false.
Let see more example for more clear question.
$var1 = '021234567'; // this is string. not integer. NOT json encoded.
$var2 = '"021234567"'; // this is json encoded.
$var3 = 021234567; // this is integer. NOT json encoded.
$var4 = 'bla bla'; // this is string. NOT json encoded.
$var5 = '{"1":"a2","a2":{"1":"a2.2","2":"a2.2"}}'; // this is json encoded.
var_dump(isJson($var1));
var_dump(isJson($var2));
var_dump(isJson($var3));
var_dump(isJson($var4));
var_dump(isJson($var5));
the results are:
true
true
true
false
true
But the expected results are:
false
true
false
false
true
The question is. How to check the string that is valid json encoded?
More example 2
If 021234567 is an integer. when i use json_encode it returns integer and have nothing to do with it again when use json_decode
$var = 021234567;
echo $var; // 4536695
echo json_encode($var); // 4536695
echo json_decode(4536695); // 4536695
echo json_decode($var); // 4536695
$var = 21234567;
echo $var; // 21234567
echo json_encode($var); // 21234567
echo json_decode(4536695); // 21234567
echo json_decode($var); // 21234567
so, the integer value should return false when i check json encoded string with isJson function. but it is not.
If 021234567 is string. when i use json_encode i should got "021234567" (with double quote). if this string has no double quote, it should not be json encoded.
$var = '021234567';
echo $var; // 021234567
echo json_encode($var); // "021234567"
echo json_decode('"021234567"'); // 021234567
echo json_decode($var); // 21234567
// example if string is text with double quote in it.
$var = 'i"m sam';
echo $var; // i"m sam
echo json_encode($var); // "i\"m sam"
echo json_decode('"i\"m sam"'); // i"m sam
echo json_decode($var); // null
As you see. the simple string with json encoded should contain at least double quote character at open and close of that string.
Please help me how to check that string is valid json encoded.
I think the valid json encoded string should at least have double quote " or curly bracket {} at the open and close of that string.
I don't know how to check that or don't know how to preg_match that.
From PHP Documentation:
PHP implements a superset of JSON - it will also encode and decode scalar types and NULL. The JSON standard only supports these values when they are nested inside an array or an object.
So, the reason leading zeros make this check pass is that json_decode just strips them during parsing without giving any errors. For example:
echo json_decode('0123');
will just display 123.
Related
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];
Here is the base64 encoded smilies generated form my android phone and saved into MySQL when I try to display it in browser first I need to check if the string is base64 encoded then I decoded and print it, but below code fails to
$mystring = "8J+YgPCfmInwn5iZ8J+YkPCflIfwn5Oi8J+OtfCfjqfwn5C18J+QiPCfpoTwn5CX8J+MjfCfl7vw\nn4+f8J+PofCfj4Himb/wn5uC8J+atA==\n";
if (base64_encode(base64_decode($mystring)) == $mystring) {
echo base64_decode($mystring);
} else {
echo $mystring;
}
but if I directly decode same string and print it works
echo base64_decode($mystring);
// output ππππππ’π΅π§π΅ππ¦πππ»ππ‘πβΏππ΄
however same code worked for iOS phone generated smiles.
$mystring = "8J+YgvCfkoHwn5iK8J+RqeKAjfCfkanigI3wn5Gn8J+ZiPCfpKPwn5mJ8J+QvPCfkLbwn5CT8J+MmeKaoe+4j/CfjY7wn42U8J+NlfCfpYPimr3vuI8=";
if(base64_encode(base64_decode($mystring)) == $mystring) {
echo base64_decode($mystring);
} else {
echo $mystring;
}
//output ππππ©βπ©βπ§ππ€£ππΌπΆππβ‘οΈππππ₯β½οΈ
I don't understand what is the problem with this block:
if(base64_encode(base64_decode($mystring)) == $mystring)
if(base64_encode(base64_decode($mystring)) == $mystring)
You cannot compare the content of two strings in that way.
Use strcmp() function.
Moreover you cannot check in this way if $mystring is base64 encoded.
You will always get true as encoding a string and then decoding the result will always deliver the original string.
Comparing wil only tell you if encoding/decoding works.
What base type returned by the function "fread()" of PHP, and how can I convert this type to be shown as hexa on the screen?
If I do it that way:
while(!feof($resource))
{
$contents = fread($resource, 1);
$new = intval($contents);
echo base_convert($new, 10, 16);
}
Its just prints a bunch of zeros on the screen...
Why its not the same as doing
$contents = fread($resource, filesize($file_text));
echo bin2hex($contents);
Which prints the normal hexa?
It's "not the same" because intval does not do what you think it does. It takes a string and interprets it as an integer. If the string has letters and such in it, it's not a valid integer, and so intval returns 0.
That function is for converting e.g. "1234567"(string) to 1234567(int).
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];
?>
Is it possible to have a JSON string containing PHP Code, and to have this string decoded?
For example, this works as it should:
$array = ["page", "is-home", $_SERVER["REQUEST_URI"] == "/"];
var_export($array);
// array (
// 0 => 'page',
// 1 => 'is-home',
// 2 => false,
// )
This, does not work:
$json = '["page", "is-home", $_SERVER["REQUEST_URI"] == "/"]';
$array = json_decode($json); // returns NULL
echo json_last_error_msg(); // Syntax error
The second example will only work if $_SERVER["REQUEST_URI"] == "/" is removed from the json string.
Is there a way to parse this string using json_decode, and if not, are there alternative methods to accomplish this?
Many thanks!
UPDATE
The $_SERVER["REQUEST_URI"] == "/" has to be parsed. I am trying to extend Blade Templating so that I can implement parsed functions such as this:
#add-request('page', 'is-home', $_SERVER["REQUEST_URI"] == '/')
UPDATE #2
To try to simplify the matter, I need to turn a string into an object.
$str = '["page", "is-home", $_SERVER["REQUEST_URI"] == "/"]'; // this is obtained by parsing the top blade extension (not important how)
From the string I need the following array:
$array = ["page", "is-home", true / false ]
Keep in mind that the original string can contain theoretically any PHP object for one of the JSON values.
I think you're on the right track, but instead of trying to "simulate" a decode by putting single-quotes, why not (for your proof of concept) first ENCODE, then 'echo' / 'print' the value that it returns, and then DECODE to see what it returns.
Why don't you use json_encode() to obtain json string??
// create json string by json_encode() from array
$json = json_encode([
"page",
"is-home",
$_SERVER["REQUEST_URI"] == "/"
]);
// decode the encoded string with no error, of course ....
$array = json_decode($json);
As you can clearly see in the output, your first array does not contain any PHP at all.
$array = ["page", "is-home", $_SERVER["REQUEST_URI"] == "/"];
automatically fills $array[2] with the boolean false, not with PHP code.
So, let's assume you can't do such a calculation on the client (in fact, you can do this calculation in javascript as well). So you would have to send it to the server as a json string (properly encoded), decode it, eval it, and post the result back into the array.
$json = '["page", "is-home", "$_SERVER[\"REQUEST_URI\"] == \"/\""]';
$array = json_decode($json);
$array[2]=eval($array[2]);
But please don't do this! It is a big security hole.
Instead, feel free to ask a new question as to how you can do this calculation in javascript as well.
For your case you could do:
$is_home = $_SERVER["REQUEST_URI"] == "/";
$json = '["page", "is-home", '. $is_home .']';
$array = json_decode($json);
That's because you are using a variable in your string which is not parsed. In addition, $_SERVER["REQUEST_URI"] == "/" returns false. Boolean false will be converted to an empty string if it is concatenated to a string.
You should rewrite your code to something like this:
// Is the request URI equal to "/"?
$reqUriTest = ($_SERVER["REQUEST_URI"] == "/");
// If boolean false is converted to a string, it will become an empty string.
// So we need to explicitly use values "true" or "false".
$reqUriStr = ($reqUriTest ? "true" : "false");
// Now we can insert $reqUriStr into the JSON string.
$json = '["page", "is-home", '.$reqUriStr.']';
$array = json_decode($json);