PHP 将文本附加到文件
这是我在站点地图文件末尾添加新条目的代码:
$add_info="
<url>
$token
<lastmod>$date</lastmod>
</url>
</urlset>";
$end_string = "</urlset>";
$length_end_string = strlen($end_string);
fseek($handle, -$length_end_string, SEEK_END);
fwrite($handle, $add_info);
可以正常工作,但有时会弄乱文件末尾,例如:
<url>
<loc>http://example.com/url1.html</loc>
<lastmod>2011-08-31</lastmod>
</url>
</url<url>
<loc>http://example.com/url2.html</loc>
<lastmod>2011-08-28</lastmod>
</url>
</urls<url>
原因可能是 php 解析器无法到达文件末尾适当地?
this is my code for adding a new entry at the end of a sitemap file:
$add_info="
<url>
$token
<lastmod>$date</lastmod>
</url>
</urlset>";
$end_string = "</urlset>";
$length_end_string = strlen($end_string);
fseek($handle, -$length_end_string, SEEK_END);
fwrite($handle, $add_info);
Which works alright but sometimes messes up the end of the file like for example:
<url>
<loc>http://example.com/url1.html</loc>
<lastmod>2011-08-31</lastmod>
</url>
</url<url>
<loc>http://example.com/url2.html</loc>
<lastmod>2011-08-28</lastmod>
</url>
</urls<url>
Could a reason for this be that php parser is unable to reach the end of file properly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
打开后添加对
flock
的调用(使用LOCK_EX
)文件。这将防止由于并发而导致的混合写入。Add a call to
flock
(withLOCK_EX
) after opening the file. This will prevent intermingled writes due to concurrency.我认为问题的原因很简单,就是你
在 $add_info 变量中。
它不应该包含 urlset 的结尾。
另外,尝试手动计算字符并将硬编码的负数放入参数中,看看会发生什么。 (一些有趣的事情可能由此而来)
I think that the cause of the problem is simply that you have
in the $add_info variable.
it should not contain a closing to the urlset.
Also, trying counting the char manually and put the hard coded negative number in the parameter and see what happens. (something interesting might come from that)
如果文件设置正确,这应该可以工作,但是,您盲目地倒回 9 个字符,因此如果文件末尾有额外的空格,这将会中断。您的
urlset
关闭标记以两种不同的方式被截断这一事实可能暗示您的文件不符合您的期望。您可能会研究验证文件指针位置的方法或使用 xml 库,如您的问题评论中提到的。
With a properly set up file, this should work, HOWEVER, you are blindly rewinding 9 characters, so if there is extra white space at the end of the file, this will break. The fact that your
urlset
close tag is truncated two different ways might be a hint that your file does not conform to your expectation.You might look into ways to validate your file pointer position or use an xml library as mentioned in the comment on your Q.