it seems to be a really easy question, but I am a little bit struggling: I am receiving a JSON String via JavaScript. Now I would like to iterate through the element. The resulting string has this form: {"title":value,"title2":value}
How can I iterate through this JSON string without knowing the key and value? I would like to get this output:
title -> value
title2 -> value2
I tried it this way:
$json = file_get_contents('php://input');
$array = json_decode($json,true);
$response = "Test";
foreach($array as $key=>$val) {
$response = $response. "$key : $val";
}
echo json_encode($response);
It only returns "Test". If I change it to echo json_encode($array), it returns the mentioned JSON String.
You mention javascript and php in your question, so I'm going to answer for both. Here is JS, two different ways. I believe that foreach is being deemphasized in favor of the (of) construct now, but I don't work primarily in JS:
var json = '{"title": 12, "title2": "text"}';
var data = JSON.parse(json);
Object.keys(data).forEach(function(key) {
console.log(key + ' -> ' + data[key])
})
for(key of Object.keys(data)) {
console.log(key + ' -> ' + data[key]);
}
And for PHP:
You can parse the json string into an array using json_decode:
$json = '{"title": 12, "title2": "text"}';
$arr = json_decode($json, true);
foreach($arr as $key=>$val) {
echo "$key : $val";
}
true parses it into an array instead of a std object.
https://www.php.net/manual/en/function.json-decode.php
Because of response's format you must decode the decoded format in order to take the object as you want
$json = '{"title": 12, "title2": "text"}';
$encoded=json_encode($json);
$decoded=json_decode($encoded);
$ddecode=json_decode($decoded);
foreach($ddecode as $key=>$val) {
echo "$key -> $val";
}
Output :
title -> 12 title2 -> text
Related
I am trying to convert a PHP function to javascript, but i cant read the following line of codes:
$sha_string .= "$key=$value$ipn_passphrase";
and
$sha_sign = strtoupper(hash("sha512", $sha_string));
Complete function:
function digistore_signature( $ipn_passphrase, $array)
{
unset($array[ 'sha_sign' ]);
$keys = array_keys($array);
sort($keys);
$sha_string = "";
foreach ($keys as $key)
{
$value = html_entity_decode( $array[ $key ] );
$is_empty = !isset($value) || $value === "" || $value === false;
if ($is_empty)
{
continue;
}
$sha_string .= "$key=$value$ipn_passphrase";
}
$sha_sign = strtoupper(hash("sha512", $sha_string));
return $sha_sign;
}
the $array is the body of a POST request.
the $passphrase is a string
.= in PHP is a simple concatenation. it is similar to the programming concept of +=. It's easy to understand with an example
<?php
$a = "hello";
$a .= " "; //now $a = "hello "
$a .= "world"; // now $a = "hello world"
"$key=$value$ipn_passphrase"; is called an in-place variable substitution in PHP. You can check the PHP Doc for more. You can simply consider it as the value $key, $values and $ipn_passphrase is replaced by the values of those variables accordingly and it forms a new string variable $sha_sign.
$sha_sign = strtoupper(hash("sha512", $sha_string)); is a simple statement where you pass the algorithm sha512 and $sha_string to the function hash() and store the result back in $sha_string variable.
I am stuck with this problem. Here is my code:
<?php
$arr = [
'from_name' => 'Rosresurs1.ru',
'from_email' => 'team#rosresurs.net',
'reply_email' => 'reply#rosresurs.net',
'subject' => 'Вас приветствует Росресурс!',
'reply_us' => 'Вопрос нам',
'charset' => 'UTF-8',
'headers' => ['List-Unsubscribe: <mailto:support#rosresurs.net?subject=Unsubscribe>, <http://rosresurs.net/escript/unsubscribe.php?token=$token>', 'Precedence: bulk']
];
echo 'Var dump array to encode: <br>';
var_dump($arr);
//Encoding
$done = json_encode($arr, JSON_UNESCAPED_UNICODE);
echo 'Echo encoded array to json: <br><br>';
echo $done . "<br><br><br><br>";
//Decoding
echo "Starting decoding from file: <br><br>";
$var = json_decode('mailconfig.json', true);
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last JSON error found: ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL . '<br><br>';
echo 'Var dump variable: <br>';
var_dump($var);
And here is the output:
And here is JSON file, from which I tried to decode json:
{"from_name":"Rosresurs1.ru","from_email":"team#rosresurs.net","reply_email":"reply#rosresurs.net","subject":"Вас приветствует Росресурс!","reply_us":"Вопрос нам","charset":"UTF-8","headers":["List-Unsubscribe: , ","Precedence: bulk"]}
As you see my array contains UTF-8 symbols, so I have encoded them with JSON_UNESCAPED_UNICODE option. But when I try to decode(FROM FILE), it fails. But when I try to decode from encoded variable $done, it works perfectly.
My json file contains the same $done output(copied from the browser and pasted to file). json_last_error said it's a syntax error. But there is no one...
Also I pasted json string from file to online json syntax verify service and it returned "A valid JSON string".
P.S. I made a lot of echo helpers(see screenshot), so you can get into a problem fast(like starting encoding and decoding points).
According to the docs, json_decode() does not take a filename as a parameter, only a string.
If you want to decode JSON from a file you would need to do something like this:
$var = file_get_contents('mailconfig.json');
$var = json_decode($var);
Or, if you have to do this a lot, you could wrap the whole thing in a function:
function file_json_decode($path, $assoc = false){
if(file_exists($path)){
$json = file_get_contents($path);
$result = json_decode($json, $assoc);
} else {
$result = null;
}
return $result
}
And then call it like this:
$var = file_json_decode('mailconfig.json', true);
You are calling json_decode on a wrong parameter. The first parameter is the JSON data, not a filename! So if you want to parse the JSON from a file, you may write
json_decode(file_get_contents('mailconfig.json'), true);
I have problems with treatment of Post. I received a string with the symbol '%' and two letters together, like 'Geci%de', but on PHP the var_dump I receive a different string, like 'Geci�', if try to use utf8_encode and utf8_decode, however the error continued, the strings resulted were 'GeciÞ' and'Geci?'. How is the better way to convert in the orignal string? I need to use in postgreSQL, it will be in select.
It is uses to treatment:
$data = strip_tags($data);
$data = trim($data);
$data = get_magic_quotes_gpc() == 0 ? addslashes($data) : $data;
$data = preg_replace("#(--|\|)#s", "", $data);
$data = urldecode($data); // especific to Ajax
return utf8_decode($data);
Am using $.get to send some values when decoding them in php they are all converted to strings even though they are numbers.
CODE:
var id_from = 19;
var id_to = 19;
$.get("save.php",{id_from:id_from,id_to:id_to }, function(){
console.log(result)
});
On the save.php
<?php
var_dump($_GET)
?>
Am getting
array(2) {
["id_from"]=>
string(1) "1"
["id_to"]=>
string(1) "4"
}
How can i get the values as integers since they are output as strings
try this:
PHP
By typecasting you can do this.
$value = "4";
$val = (int) $value;
echo var_dump($value); //string(1) "4"
echo var_dump($val); // int(4)
You can use the intval() function to convert it to int
<?php
echo intval($_GET['id_from'])."|".$_GET['id_from'];
?>
You can type cast in PHP Server side.
$id_from = (int) $_GET['id_from']
I have a text file that has json on it. example below:
{'something' : 'ss'}
I am trying to read it on php and convert it to an array using json_decode.
$temp = '';
$fh = fopen( '/quiz' . $testid . '.txt' ,'r');
while ($line = fgets($fh)) {
$temp .= $line;
}
fclose($fh);
$temp = str_replace("\n","",$temp); //to remove new line
$temp = str_replace("\r","",$temp);
$temp = json_decode($temp);
But im getting null
If I don't json_decode it.. I can get the string.
I hope anyone can help me with this.
Thanks,
E
You don't need to do any parsing prior to calling json_decode
$contents = file_get_contents('/quiz' . $testid . '.txt');
$temp = json_decode($contents);
If you're still getting null, your JSON is likely invalid, you can use json_last_error to diagnose it.
This snippet works so i think that's a problem with your file parsing algorithm
<?php
$temp = '';
$temp='{
"a":1,
"b":[1,2,3]
}';
$temp = str_replace("\n","",$temp); //to remove new line
$temp = str_replace("\r","",$temp);
$temp = json_decode($temp);
var_dump($temp);
?>
As documented:
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
The reason is that you don't have valid JSON.
Parse error on line 1:
{ 'something': 'ss'}
-----^
Expecting 'STRING', '}'
You probably mean:
{
"something": "ss"
}