php - 从我的 WordPress 插件写入文件

标签 php file-io wordpress

我为我的 WordPress 网站编写了一个自定义插件,该插件依赖于从插件文件夹中的 xml 数据文件读取/写入。当我测试这个用于文件读/写的标准 PHP 代码时,它会让我创建/写入位于 wp-admin/级别的文件,但不是插件文件夹中的文件,尽管它可以从两者读取。

$file = 'test.xml';  (Can write to this file)
$file = plugins_url()."/my-plugin/test.xml";  (Can read but not write to this file)
// Open the file to get existing content
$current = file_get_contents($file);
echo $current;
// Append a new person to the file
$current .= "<person>John Smith</person>\n";
// Write the contents back to the file
file_put_contents($file, $current);

我收到以下调试错误:

Warning: file_put_contents(http://localhost/wp_mysite/wp-content/plugins/my-plugin/test.xml) [function.file-put-contents]: failed to open stream: HTTP wrapper does not support writeable connections in /Applications/MAMP/htdocs/wp_mysite/wp-content/plugins/my-plugin/my-plugin.php on line 53

我目前正在本地 MAMP 服务器上运行它,但想要一个能让我在任何 WordPress 服务器上打包和发布插件的解决方案。什么是正确的方法?

谢谢-

最佳答案

如果您想写入文件,请不要通过 HTTP 访问它。直接访问它而不是读取和写入,因为它是访问文件的更快和最直接的方法。

要获取基本插件目录路径,请使用 WP_PLUGIN_DIR 常量:

$file = 'test.xml';  // (Can write to this file)
$file = WP_PLUGIN_DIR."/my-plugin/test.xml"; 
//      ^^^^^^^^^^^^^

这将阻止您使用 HTTP,由于性能原因和 HTTP 不支持写入,根本不应该使用 HTTP。但最重要的是,由于它是您有权访问的服务器上的一个文件,因此请直接访问它。

关于php - 从我的 WordPress 插件写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6505700/

相关文章:

javascript - Nodejs 文件流并发

php - 无法选择当前数据库名称

javascript - <p> JS/CSS 文本翻转器中的间距问题

java - 使用 JDBC Java 字符串,在 PHP 中连接到 mysql 数据库

php - 尝试在 kitematic 上为 docker 设置 lamp 和 wordpress

PHP 5.3 lambda 匿名函数不工作

php - WooCommerce 管理员按 SKU 搜索产品

php - 上传缺少文件扩展名

java - 如果我在其中放入字符,HashMap 中的 containsKey 方法会检查整数吗?

java - 从文本文件中获取字符串并将每一行分配给值(一次 2 个并插入到 LinkedHashMap 中)