D
D
denisyukphp2011-03-21 13:17:24
PHP
denisyukphp, 2011-03-21 13:17:24

How to write values ​​from a text file to an array in PHP?

Below is a piece of code that searches the $search array for a specific value, in my case “google.com” , and then displays a condition on the screen.

<?php

$search = array("yandex.ru", "google.com");

if (in_array("google.com", $search)) {
    echo "есть";
}

else {
    echo "нету";
}

?>

But I have a large text file base.txt , a kind of site database, which needs to be written to the $search array and treated like a regular array.

yandex.ru
google.com
bing.com
rambler.ru
yahoo.com

Solution found :

<?php

$data = file_get_contents("base.txt");
$search = explode("\r\n", $data);

if (in_array("google.com", $search)) {
    echo "есть";
}

else {
    echo "нету";
}

?>

- More solutions?

Answer the question

In order to leave comments, you need to log in

9 answer(s)
Z
zizop, 2011-03-21
@zizop

Well, or just $result = file("base.txt");
It already collects lines in an array. php.net/manual/en/function.file.php

N
nikita2206, 2011-03-21
@nikita2206

If the file is very large, then it makes sense not to create an array, but simply run through the lines in a loop without clogging the RAM ...

R
RomAndry, 2011-03-21
@RomAndry

as an option

$base = file("base.txt");
$result = array();

foreach($base AS $row) {
  $result[] = $row;
}

V
Vasya_Sh, 2011-03-21
@Vasya_Sh

<?php
$array = file($filename, FILE_IGNORE_NEW_LINES);

flag - so that the hyphen does not fall into the string

M
Melanitsky, 2011-03-21
@Melanitsky

explode("\n", file_get_contents('file_name'));

D
Denis Turenko, 2011-03-21
@Dennion

$content = file_get_contents('base.txt');
$base = explode('\r',$content);
print_r($base);

Depending on how the file was created, you may need to write explode('\r\n',$content);

Z
Zakharov Alexander, 2011-03-21
@AlexZaharow

Maybe using regular expressions will be faster?:
$content = file_get_contents('base.txt');
$search = '/^<what are we looking for>$/'; // ^start, $end of string when searching using regular expressions.
$fp = fopen('base.txt');
if( preg_match($pattern, $content) )
{
if any;
}
else
{
and if there are no matches;
}

W
wanmen, 2011-03-21
@wanmen

1) If the match is exact, then it's better to use file().
2) If you need to work with templates, ie. some parts of the string are not known to us, then file_get_contents and PCRE are better

D
denisyukphp, 2011-03-21
@denisyukphp

A possible option, but I have no way to compare the speed now.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question