PHP JSON函数在作为CLI脚本调用时不可用


PHP JSON functions not available while being called as CLI script?

我注意到了一些事情,但我不确定为什么这是真的,或者为什么它与标准脚本不同,也许有人可以帮我解开这个谜。当从命令行运行一个包含json_*函数的PHP脚本作为可执行文件时,我会得到一个Fatal error: Call to undefined function json_encode() in /var/www/jsontest.php on line 6,该脚本位于以下

#!/usr/bin/php -n
<?php
$arr = array('foo', 'bar', 'baz');
print_r($json = json_encode($arr));
print_r(json_decode($bar));

当试图解码标准的干净json输入(通过jsonint验证)时,json_decode()也会发生这种情况

上面的脚本在Linux/DEB终端中运行如下。。。

$ chmod +x jsontest.php
$ ./jsontest.php

不过,通过我的本地Web服务器运行它,我收到了预期的输出

#!/usr/bin/php -n ["foo","bar","baz"]Array ( [0] => foo [1] => bar [2] => baz ) 

发生了什么事?为什么JSON在被解释为可执行文件时不可用?

PHP版本是PHP 5.5.3-1ubuntu2 (cli) (built: Oct 9 2013 14:49:24),任何想要它的人都可以在我的Ubuntu One Account 上发布PHPInfo

我猜这里的问题是您的php.ini文件-PHP在作为CLI运行时使用不同的ini文件。看看爆炸药丸对这个问题的回答:

从命令行运行php时,可以使用-c或--php.ini参数,指向要使用的php.ini文件。这将允许您同时使用一个php.ini文件。您也可以将php别名为php-c/path/to/php.ini(如果您自己运行脚本)。