Y
Y
Yaroslav Studenikin2020-09-04 13:09:28
PHP
Yaroslav Studenikin, 2020-09-04 13:09:28

How to write arrays with foreach to a file, and get it right?

Hello!
Faced the following problem:
Looping through an array:

foreach($selectedProxiesCountry as $proxy) {

                file_put_contents($filename, serialize($proxy), FILE_APPEND);
        }

Inside the code there is more, The task is to write the arrays I need to a file, one by one (I use FILE_APPEND).
As a result, a single array for writing looks like this:
Array
(
    [ip] => 185.64.209.18
    [port] => 8080
    [hostname] => 185.64.209.18
    [http] => 0
    [https] => 1
    [socks4] => 0
    [socks5] => 0
    [level] => 1
    [yandex] => 0
    [google] => 0
    [mailru] => 1
    [twitter] => 1
    [country_code] => RU
    [response] => 257
    [good_count] => 5
    [bad_count] => 1
    [last_check] => 2020-09-04 14:48:32
    [city] => Кстово
    [region] => Нижегородская область
    [real_ip] => 185.64.209.18
    [test_time] => 0.8
    [me] => 0
)

Everything is written to a file, excellent. But when I want to get from there:
$readyProxiesArr = unserialize(file_get_contents($proxyFile));

throws ErrorException' with message 'unserialize(): Error at offset 0 of (17865 bytes)
I tried to write in json format, as far as I understand, it incorrectly writes arrays from the loop one by one.
Please help, thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tendor, 2020-09-04
@yar_stun

You collect everything you need to write into one array and write it down. And so in your file, serialized arrays lie one after another in text.
If you need to filter - filter the necessary data, collect a new array and save it entirely.

file_put_contents($filename, serialize($selectedProxiesCountry));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question