Scroll through a .txt file and extract a "PK" from the file

0

I started shortly with programming in PHP and I have some difficulty in understanding some functions anyway, I'm participating in a project, and as part of the project I need to store a array I want to use the serialize function so that it can write the array to a file ).

My difficulty is:

1) How do I read the file? A: functions arquivo.txt ? Blz, how do I scroll through this file and retreat only a fopen() , exactly a string of that file?

$conteudo = serialize($array);      
$caminho ='';
file_put_contents($caminho, $conteudo);

Content of array saved:

PK

    
asked by anonymous 04.10.2016 / 17:42

1 answer

0

If it's just to extract the string number, you can do just that:

$value =  'a:1:{s:5:"items";a:1:{i:0;a:1:{s:2:"pk";i:1338838365890273563;}}}';

preg_match('/"pk"\;i\:([0-9]+)\;/', $value, $d);

echo $d[1];

Now if you want to revise the value of the array, you can roll back the serialize like this:

$conteudo_salvo = 'a:1:{s:5:"items";a:1:{i:0;a:1:{s:2:"pk";i:1338838365890273563;}}}';
echo unserialize($conteudo_salvo)['items'][0]['pk'];

However, there is a problem that can change the behavior of the conversion, that is, the serialized number is converted to scientific notation, that is, the whole integer reference is lost:

 $a = array(
         'items' => array( 
                     0 => array( 'pk' => 1338838365890273563
                          ) 
                   )
    );

Out of unserialize , it will look like scientific notation because the value is too large to be serialized: 1.3388383658903E + 18
 How to make serialize done correctly, pass it in string format:

$a = array(
         'items' => array( 
                     0 => array( 'pk' => "1338838365890273563"
                          ) 
                   )
    ); 

By doing this, simply use the functions this way:

$s = serialize($a);
$u = unserialize($s);

print_r($a);
print_r($u);

OBS: Three simple ways to transform integer value to string:

$a["items"][0]["pk"] = '"' . $a["items"][0]["pk"] . '"'; 

or

$a["items"][0]["pk"] = (string) $a["items"][0]["pk"];

or

$a["items"][0]["pk"] = strval($a["items"][0]["pk"]);
    
04.10.2016 / 22:41