簡體   English   中英

為什么目錄正確時file_get_content無法找到文件?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM