【问题标题】:Why does file_get_content fails to locate file when the directory is correct?为什么目录正确时file_get_content找不到文件?
【发布时间】:2022-01-11 17:38:24
【问题描述】:

我有一个测试短代码来读取 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 响应。

按照How to Fix The Invalid JSON Error in WordPress (Beginner's Guide)的文章,我激活Health Check & Troubleshooting,使用Classic Editor将调试代码添加到wp-config.php中:

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );

结果如下:

警告:file_get_contents(./node.json):无法打开流:第 67 行的 /home/xnqucuhr5aza/public_html/wp-content/plugins/Custom 1/Custom plugin.php 中没有这样的文件或目录

为什么会这样?该文件与插件位于同一目录中(即/home/xnqucuhr5aza/public_html/wp-content/plugins/Custom 1/node.json)。然后我尝试file_get_contents(__DIR__ . '/node.json');,但它只是说NULL,没有别的。

【问题讨论】:

  • 看起来像一个相对路径,你确定它是从每个请求的相同位置加载的吗?您确定文件本身以字符./ 开头吗?
  • 我想你错过了我的要求,文件没有移动,但它正在寻找的地方可能,使用绝对路径不是更安全吗?例如__DIR__ . '/node.json'?
  • 因为您正在加载的 URL 发生了变化,我也避免加载 URL,而是使用绝对文件路径。你也确定这属于这个堆栈吗?这些看起来都不是与 WordPress 相关的,而是一般的 PHP
  • @Ooker “可能是 json_decode,它是空的” - 你可以通过 var_dump( json_decode($strJsonFileContents, true) ); 来确认。友情提醒,var_dump() 回显输出,所以不需要 echo 就像 echo var_dump.. 您还可以验证您的 JSON 语法(即 $strJsonFileContents 的值),例如使用像jsonlint.com这样的在线工具,如果语法很好,那么PHP也会解析数据而不返回null或抛出错误✌
  • manual 实际上是说,“如果json 无法解码编码数据深度超过嵌套限制,则返回null /i>",所以检查嵌套限制?

标签: php shortcode json posting


【解决方案1】:

“不是有效的 JSON 响应”错误是因为您的短代码编写不正确。

As documented,短代码需要返回它们的输出。否则,它将在 WordPress 处理短代码后立即打印,也就是在它们输出之前。

在这种情况下,它会导致在编辑器中 API 响应的开头打印短代码的输出,从而破坏该响应的格式。

您需要返回简码的输出:

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 buffering 来捕获输出并返回它。

【讨论】:

  • 我明白了。但即使我使用绝对文件路径 (file_get_contents(__DIR__ . "/node.json")),它仍然返回 NULL
  • 我不知道你项目的结构。这段代码的文件路径是什么,json文件的路径是什么。我注意到您的插件目录中有一个空格。这可能是个问题。无论如何,这是一个 PHP 问题,与 WordPress 无关。
  • 我删除了空间,这个错误仍然存​​在。文件的路径现在是/home/xnqucuhr5aza/public_html/wp-content/plugins/Custom/Custom plugin.php,json 文件的路径现在是/home/xnqucuhr5aza/public_html/wp-content/plugins/Custom/node.json。至少看起来插件找到了json文件?
猜你喜欢
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 2021-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多