加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 18:19:17 所属栏目:PHP教程 来源:网络整理
导读:我为我的WordPress网站编写了一个自定义插件,它依赖于从插件文件夹中的xml数据文件读取/写入.当我测试这个标准的 PHP代码进行文件读/写时,它会让我创建/写入位于wp-admin / level的文件,但不能创建/写入插件文件夹中的文件,尽管它可以从两者中读取. $file =
我为我的WordPress网站编写了一个自定义插件,它依赖于从插件文件夹中的xml数据文件读取/写入.当我测试这个标准的 PHP代码进行文件读/写时,它会让我创建/写入位于wp-admin / level的文件,但不能创建/写入插件文件夹中的文件,尽管它可以从两者中读取.
$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不支持写入.但最重要的是,因为它是您可以访问的服务器上的文件,所以直接访问它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读