bir satır (php) dosya imlecini hareket?

4 Cevap php

Ben içeriği sürekli değişiyor beri benim sitede sitemap.xml dosyası otomatik çalışılıyor. Ben etiketleri yeni bir dizi ekleyebilir fopen($file_name, 'a'); ki: Ben şu anda ekleme için dosyayı açın. Ancak, ben sadece tüm site haritası dosyası ben dosyayı açmak her zaman, ben ucundan değil dosyanın sonuna metin eklemek gerekir, ancak 1 satır anlamına gelir bir etiketi ile sona gerektiğini fark ettim.

Yani temelde, ben bunu başarmak böylece ben dosya işaretçisi ekleme için dosyayı açtıktan sonra nasıl hareket edebilirsiniz? Teşekkürler.

Update: burada site haritası gibi görünüyor budur:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.google.com/schemas/sitemap/0.84">
	<url>
		<loc>...</loc>
		<lastmod>2009-08-23</lastmod>
		<changefreq>weekly</changefreq>
		<priority>0.8</priority>
	</url>
    </urlset>

Ben append zaman yani, ben sağ kapanış </urlset> etiketi önce gitmek gerekir <url>..</url> bölümünü eklemeniz gerekir. Zaten dosyanın sonuna xml ekleyebilirsiniz kodu var. Ben sadece yeni bölümünü right before kapanış etiketi eklemek için nasıl anlamaya gerekir.

4 Cevap

fseek () dosyanın sonuna aramaya (kullanarak bulmak filesize ()) php kullanın, sonra geriye doğru bir satır yineleme. son satırı okumak ve geçici saklayın. Eklemek istediğiniz ne son satırın üzerine, o zaman önceden depolanan geçici satır eklemek.

Geriye tek bir satır yinelemek için, fseek fgetc () ile birlikte kullanın

$offset = filesize($fhandle) - 1;
fseek($fhandle, $offset--); //seek to the end of the line
while(fgetc($fhandle) != '\n') {
   fseek($fhandle, $offset--);
}

ve şimdi dahili dosya işaretçisi son satırından önce bir çizgiye işaret olmalıdır. ders dışı size dosya tek bir satır olduğunda köşe durumlarda uğraşmak gerekecek, ama ayrıntıları anlamaya izin vereceğim ;)

Şimdi tmp değişkene son satırı saklamak

$lastline = fgets($fhandle);
fseek($fhandle, $offset); //go back to where the last line began

hattınızı takın ve dosyanın sonundaki son satırı append

fwrite($fhandle, $myLine);
fwrite($fhandle, $lastline);

Sen neden bahsediyorsun XML görmeden, ve (cevaba kodlu tam bu veriniz) eklemek için çalışıyoruz ne bilmeden bu yaklaşım önerebilir ...

  1. PHP XML çözümleyici kullanarak tüm dosya yüklemek (http://uk3.php.net/manual/en/ref.xml.php)
  2. XML içine yeni bir öğe eklemek
  3. () Fonksiyonları (Ben senin zaten bu biraz yapıyor tahmin ediyorum) fopen () ve fwrite kaydetmek

Dediğim gibi, XML veya biraz daha kod görmeden onun çok sağlamak için sert ve cevap

Charles Ma'nın cevap ekleme. Eğer aynı anda yazıyor olabilir eğer () sitemapper.php adlı bir dosyada bu kaydedebilir ve bir GET sorgu ile bu dosyayı diyoruz, ben size daha fazla güvenlik eklemek için tavsiye ederiz, ancak, ve akın edebilir.

Eğer SimpleXMLParser yok PHP4 kullanıyorsanız bu kullanmak için başka bir nedeni olacaktır.

<?php
/*--------------------------------------------------------
==================
sitemapper.php 1.0
==================
Pass me a path to a page, and I will add it to your XML sitemap.

Paths are passed from root, as 
www.example.com/sitemapper.php?path=/test/index.html
for a page at http://www.example.com/test/index.html

This script is faster than parsing XML, for large sitemaps.
--------------------------------------------------------*/

if (isset($_GET[path])) {

    // Get the path to the new page to add to our sitemap.
    $fname = urldecode($_GET[path]);

    // Real path to files is different on some hosts.
    $current_path = realpath(dirname(__FILE__));

    if (!is_file("./sitemap.xml")){

        $xml = '';
        $xml =  "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"."\n";
        $xml .= "<urlset 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\" xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"."\n";
        $xml .= "</urlset>"."\n";

        $sitemap = fopen("./sitemap.xml", "x");             
        fwrite($sitemap, $xml); 
        fclose($sitemap);
    }

    // Write sitemap.xml entry for current file
    // This is a very old-school 'C' style of doing it.
    // The modern way would be to open the file in an XML parser, 
    // add the elements you want, serialise it to a new file 
    // and swap them over (so that nothing reads the XML in 
    // the middle of you writing it)
    //
    // However I expect this XML file to become *huge* shortly
    // So I am avoiding use of the PHP XML Parser.

    $date = date('Y-m-dTH:i:sP', time()); //Date in w3c format for XML sitemaps

    $xml = '';
    $xml .= "<url>"."\n";
    $xml .= "   <loc>http://". $_SERVER["HTTP_HOST"] . $fname . "</loc>"."\n";
    $xml .= "   <lastmod>" . $date . "</lastmod>"."\n";
    $xml .= "   <priority>0.50</priority>"."\n";
    $xml .= "   <changefreq>never</changefreq>"."\n";
    $xml .= "</url>"."\n";            

    if ($sitemap = @fopen("./sitemap.xml", "r+")) 
    {

        // seek to the end of the file, then iterate backwards one line. 
        // read the last line and store it temporarily. overwrite the 
        // last line with what you want to insert, then append the 
        // temporary line you stored previously.

        $offset = filesize("./sitemap.xml") - 1;

        fseek($sitemap, ($offset - 1)); //seek to before the last character in the file
        while( (($char = fgetc($sitemap)) !== "\n") && ($offset > -2000) && ($offset < 2000)) {
            // Go backwards, trying to find a line-break.
            // The offset range is just a sanity check if something goes wrong.
            $offset = $offset - 1;
            fseek($sitemap, $offset);
        }  

        $offset = $offset + 1; // Come to the beginning of the next line
        fseek($sitemap, $offset);
        $lastline = fgets($sitemap); // Copy the next line into a variable
        fseek($sitemap, $offset); //go back to where the last line began

        fwrite($sitemap, $xml); // add the current entry
        fwrite($sitemap, $lastline); // add the </urlset> line back.

        fclose($sitemap);
    }
}
?>

fseek ($ fp,-n, SEEK_END), ama 'r +' değil, 'a' olarak dosyayı açması gerekir.

Genellikle bu gibi XML işleme için iyi bir fikir değil; tam bayt pozisyonlarına dayanarak çok kırılgandır. Daha iyi, XML çözümleyici dosyayı açmak istediğiniz öğeler eklemek, yeni bir dosyaya tefrika ve (hiçbir şey yazmanın ortasında XML okur, böylece) onları değiş tokuş etmek olacaktır.

Bir veritabanı destekli sitesinde, aynı zamanda PHP kendisi kullanarak dinamik sitemap XML oluşturma düşünebiliriz.