
PHP ile satır satır okumak isteyebileceğiniz iki neden vardır. Birincisi, üzerinde çalıştığınız proje, dosyayı her seferinde bir satır işlemenizi gerektiriyor. İkincisi, çok büyük bir dosya okuyorsunuz ve onu hafıza sınırını aşmadan okumanın tek yolu, her seferinde bir satır yapmak.
kullanma file()
Dosyayı Okumak
kullanabilirsiniz file()
PHP’de tüm dosyayı bir kerede bir diziye okumak için işlev. Dizi öğeleri, dosyanın ayrı satırlarıdır. Böylece dizi üzerinde yineleme yaparak dosyadaki satırları yineleyebileceksiniz. İşlev üç parametreyi kabul eder:
- dosya adı: Bu, okumak istediğiniz dosyadır. Dosya adı olarak bir URL de sağlayabilirsiniz.
-
bayraklar: Bu isteğe bağlı bir parametredir ve aşağıdaki sabit değerlerden birine veya daha fazlasına ayarlanabilir:
FILE_USE_INCLUDE_PATH
,FILE_IGNORE_NEW_LINES
veFILE_SKIP_EMPTY_LINES
. - bağlam: Bu aynı zamanda bir akışın davranışını değiştirmek için kullanılan isteğe bağlı bir parametredir.
kullanacağız FILE_SKIP_EMPTY_LINES
Bir dosyadaki tüm boş satırları atlamak için bayrak. Ayrıca kullanmak isteyebilirsiniz FILE_IGNORE_NEW_LINES
tek tek satırlardan satır sonlarını kaldırmak için.
Bu işlev, başarılı olduğunda dosya içeriğiyle bir dizi döndürür ve false
başarısızlık üzerine. Ayrıca bir E_WARNING
dosya yoksa seviye hatası. İşte bu işlevin kullanımına bir örnek.
<?php $lines = file('pride-and-prejudice.txt'); $count = 0; foreach($lines as $line) { $count += 1; echo str_pad($count, 2, 0, STR_PAD_LEFT).". ".$line; } ?>
Yukarıdaki kodun çıktısı şöyle görünür:
01. The Project Gutenberg eBook of Pride and Prejudice, by Jane Austen 02. 03. This eBook is for the use of anyone anywhere in the United States and 04. most other parts of the world at no cost and with almost no restrictions 05. whatsoever. You may copy it, give it away or re-use it under the terms 06. of the Project Gutenberg License included with this eBook or online at 07. www.gutenberg.org. If you are not located in the United States, you 08. will have to check the laws of the country where you are located before 09. using this eBook. 10. 11. Title: Pride and Prejudice 12. 13. Author: Jane Austen 14. 15. Release Date: June, 1998 16. [Most recently updated: August 23, 2021]
Çıktıda bazı boş satırlar olduğunu görebilirsiniz, kullanarak onlardan kurtulabiliriz. FILE_SKIP_EMPTY_LINES
bayrak. Ayrıca, belirgin olmayabilir ancak yukarıdaki satırlar yeni satır karakterini içeriyor. Bu yüzden satırları tekrarlarken kendi satırsonu karakterimizi eklemek zorunda kalmadık. kullanarak boş satırlardan kurtulabilirsiniz. FILE_IGNORE_NEW_LINES
bayrak.
<?php $lines = file('pride-and-prejudice.txt', FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES); $count = 0; foreach($lines as $line) { $count += 1; echo str_pad($count, 2, 0, STR_PAD_LEFT).". ".$line; } ?>
Bu bayraklarla çıktı şöyle görünecektir:
01. The Project Gutenberg eBook of Pride and Prejudice, by Jane Austen 02. This eBook is for the use of anyone anywhere in the United States and 03. most other parts of the world at no cost and with almost no restrictions 04. whatsoever. You may copy it, give it away or re-use it under the terms 05. of the Project Gutenberg License included with this eBook or online at 06. www.gutenberg.org. If you are not located in the United States, you 07. will have to check the laws of the country where you are located before 08. using this eBook. 09. Title: Pride and Prejudice 10. Author: Jane Austen 11. Release Date: June, 1998 [eBook #1342] 12. [Most recently updated: August 23, 2021]
Kullanmak file()
işlevi, bellek kullanımı konusunda endişeleriniz yoksa PHP’de bir dosyayı satır satır okumanın kolay bir yoludur. Ancak, bellek kullanımı bir sorunsa daha yaratıcı olmanız gerekir çünkü file()
tüm dosyayı bir kerede bir diziye okur.
kullanma fgets()
Dosyayı Okumak
PHP ile satır satır bir dosyayı okumanın başka bir yolu da fgets()
işlev. Geçerli bir dosya tanıtıcısı olan gerekli bir parametreye sahiptir. kullanacağız fopen()
dosya tanıtıcısına erişim sağlamak için işlev. İşte çalıştıracağımız kod:
<?php $file_handle = fopen('pride-and-prejudice.txt', 'r'); function get_all_lines($file_handle) { while (!feof($file_handle)) { yield fgets($file_handle); } } $count = 0; foreach (get_all_lines($file_handle) as $line) { $count += 1; echo $count.". ".$line; } fclose($file_handle); ?>
İlk satırda dosyamızı salt okunur modda açıyoruz. Daha sonra, kabul eden bir fonksiyon tanımlarız. $file_handle
parametre olarak ve tek bir satır geri verir. kullandığımızı lütfen unutmayın. yield
ifade ve fonksiyonumuz get_all_lines()
bir üreteç fonksiyonudur. hakkında okumak isteyebilirsiniz PHP’de jeneratör işlevleri daha önce kullanmadıysanız.
kullanıyoruz feof()
içeride işlev get_all_lines()
dosya işaretçimizin dosyanın sonuna ulaşıp ulaşmadığını kontrol etmek için. Sadece dosyanın sonunda olmadığımız sürece boyun eğiyoruz. Yukarıdaki kodu çalıştırarak aşağıdaki çıktıyı almalısınız:
1. The Project Gutenberg eBook of Pride and Prejudice, by Jane Austen 2. 3. This eBook is for the use of anyone anywhere in the United States and 4. most other parts of the world at no cost and with almost no restrictions 5. whatsoever. You may copy it, give it away or re-use it under the terms 6. of the Project Gutenberg License included with this eBook or online at 7. www.gutenberg.org. If you are not located in the United States, you 8. will have to check the laws of the country where you are located before 9. using this eBook. 10. 11. Title: Pride and Prejudice 12. 13. Author: Jane Austen 14. 15. Release Date: June, 1998 16. [Most recently updated: August 23, 2021]
Çıktılar önceki bölümümüzle aynı görünüyor. Bu seferki tek fark, artık hafızanın tükenme tehlikesiyle karşı karşıya kalmamanız.
daha önce bahsetmiştim fgets()
bir seferde dosyanın bir satırını okumanıza izin verir ve sadece okumak istediğiniz dosya için dosya işaretçisine işaret eden tek bir parametre gerektirir. Bu durumda bellek tüketimi, hattın uzunluğuna bağlı olacaktır ve küçük bir belleğinizin bitme ihtimali vardır.
Ancak, alışılmadık derecede uzun satırlar içeren bir metin dosyası okuduğunuzu varsayalım. Daha sonra isteğe bağlı ikinci bir parametreyi fgets()
Okumak istediğiniz karakter sayısını belirten işlev. O zaman okuyacak length - 1
durdurmadan önce dosyadan bayt. Bir satırsonu veya dosya sonu ile karşılaşırsa daha erken duracaktır. Bu, kodunuzun bellek tüketimi üzerinde size daha fazla kontrol sağlar.
Son düşünceler
Bu eğitimde PHP ile satır satır dosya okumanın iki yöntemini tartıştım. Bunu yapmanın birkaç yolu daha var ama bu ikisi neredeyse tüm ihtiyaçlarınızı karşılayacak. Kullan file()
bellek tüketimi bir sorun olmadığında işlev görür ve kullanılır fgets()
hafızadan tasarruf etmek istiyorsanız bir jeneratör fonksiyonu ile.