I have made a code that works however it doesn't work when I try to echo a variable in the json/array. Can anyone help?
Code that works
$data = array("ips" => ["ip" => "1.1.1.1"]);
$data_string = json_encode($data);
Code that doesn't work
$test=1.1.1.1
$data = array("ips" => ["ip" => "$test"]);
$data_string = json_encode($data);
The code just return with 500error on browser
As you can see i am trying to introduce a variable. Can anyone help?
You have syntax error in $test
variable. You can use string type, like this:
$test = '1.1.1.1';
$data = array("ips" => ["ip" => "$test"]);
$data_string = json_encode($data);
you need to put quotes around "1.1.1.1", or php's parser doesn't interpret it as a string (which is what it's supposed to be)
DO THIS:
$test="1.1.1.1";
$data = array("ips" => ["ip" => "$test"]);
$data_string = json_encode($data);
NOT THIS:
$test=1.1.1.1
$data = array("ips" => ["ip" => "$test"]);
$data_string = json_encode($data);
Also it's bad practice to mix the shorthand for arrays with the array function, you should either do array("ips" => array("ip" => "$test"));
or ["ips" => ["ip" => "$test"]];
While the right answers are already given: You have a syntax error there and should write
$ip = "1.1.1.1";
I would recommend that you first take a look at your server's error logs for the web server and PHP. It will clearly state why your script is failing:
[Sat May 16 13:26:20.744739 2020] [proxy_fcgi:error] [pid 1653:tid 140650782840576] [client ::1:55866] AH01071: Got error 'PHP message: PHP Parse error: syntax error, unexpected '.1' (T_DNUMBER) in /var/www/html/stackoverflow.php on line 2\n', referer: http://localhost/
Alternatively you can use php myScript.php
and run this from the console and get the same error message. Naturally, the possible use of the PHP-CLI depends a bit on the complexity of your script.
This will help yourself in the future to find those errors easier.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.