![](/img/trans.png)
[英]file_get_content: failed to open stream: No such file or directory
[英]Why does file_get_content fails to locate file when the directory is correct?
我有一个测试简码来读取 JSON 文件:
function test( ) {
$strJsonFileContents = file_get_contents("./node.json");
$array = json_decode($strJsonFileContents, true);
echo var_dump($array); // print array
}
add_shortcode( 'test', 'test' );
将此短代码添加到帖子中,由于错误,我无法更新它
更新失败。 该响应不是有效的 JSON 响应。
在文章如何修复 WordPress 中的无效 JSON 错误(初学者指南)之后,我激活了运行状况检查和故障排除,使用经典编辑器将调试代码添加到 wp-config.ZE63407626E81E40
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
这是结果:
警告:file_get_contents(./node.json): failed to open stream: No such file or directory in /home/xnqucuhr5aza/public_html/wp-content/plugins/Custom 1/Custom plugin.php on line 67
NULL
为什么会这样? 该文件与插件位于同一目录中(即/home/xnqucuhr5aza/public_html/wp-content/plugins/Custom 1/node.json)。 然后我尝试file_get_contents(__DIR__. '/node.json');
但它只是说NULL
而没有别的。
“不是有效的 JSON 响应”错误是因为您的短代码写入不正确。
如文件所述,短代码需要返回其 output。 否则,它将在 WordPress 处理短代码后立即打印,即在它们是 output 之前。
在这种情况下,它会导致您的简码的 output 打印在编辑器中 API 响应的开头,从而破坏了该响应的格式。
您需要返回简码的 output:
function test( ) {
ob_start();
$strJsonFileContents = file_get_contents("./node.json");
$array = json_decode($strJsonFileContents, true);
var_dump($array); // print array
return ob_get_clean();
}
add_shortcode( 'test', 'test' );
因为您使用的是仅打印的var_dump()
,所以我使用了 output 缓冲来捕获 output 并将其返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.