PHP新建文件和生成xml网站地图
## 1. fopen() 打开文件 文件不存在就新建文件语法格式: __```fopen(filename,mode,include_path,context)```__ * filename > 必需。规定要打开的文件或 URL * mode: > 必需。规定要求到该文件/流的访问类型。[参数地址](:http://www.w3school.com.cn/php/func_filesystem_fopen.asp) * include_path: > 可选。如果也需要在 include_path 中检索文件的话,可以将该参数设为 1 或 TRUE。 * context: > 必需。可选。规定文件句柄的环境。Context 是可以修改流的行为的一套选项。 * __默认生成的文件在根目录__ 2. fopen() 函数打开失败返回false 可能有以下情况: * PHP配置中 open_basedir= 前面的分号删除 重启环境 * 文件路径不正确 * 打开文件模式不正确
具体代码:
//框架:ThinkPHP3.2
//文件名称
$path = 'Sitemap.xml';
//判断文件是否存在
if (!is_file($path)) {
//不存在则创建 并且赋予权限
touch($path, 0777);
}
//打开文件
$file = fopen('Sitemap.xml', 'w');
//写入内容
fwrite($file, $str);
//判断是否关闭
$close = fclose($file);
if ($close) {
$this->success('网站地图生成成功', U('Index/index'));
} else {
$this->error('生成错误,请联系管理员', U('Index/index'));
}
生成xml文件
- uelset:必填 链接集合定义入口 - url:必填 某个链接的入口 - loc:必填 页面链接地址 - lastmode:必填 链接最后更新时间 - changefreg:选填 更新频率 参数有: * always :经常改变 * hourly :每小时更新一次 * daily :一天更新一次 * weekly :一周更新一次 * monthly :一分钟更新一次 * yearly :一年更新一次 * never :从不改变 - priority:选填 权重值 0.0-1.0 之间代码:
$str = '<?xml version="1.0" encoding="utf-8"?>' . "
";
$str .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">'."
";
foreach ($article as $v) {
$str .= " " . '<url>' . "
";
$str .= " " . '<loc>' . $v['url'] . '</loc>' . "
";
$str .= " " . '<priority>' . $priority . '</priority>' . "
";
$str .= " " . '<lastmod>' . date('Y-m-d') . '</lastmod>' . "
";
$str .= " " . '<changefreq>' . 'always' . '</changefreq>' . "
";
$str .= " " . '</url>' . "
";
$str.='</urlset>';