开发者

PHP append text to file

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($ha开发者_StackOverflow中文版ndle, $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?


Add a call to flock (with LOCK_EX) after opening the file. This will prevent intermingled writes due to concurrency.


I think that the cause of the problem is simply that you have

</urlset>

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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜