Writing Array to File in php And getting the data

后端 未结 4 987
忘了有多久
忘了有多久 2021-02-05 21:38

I have An array which looks like following after using print_r

Array ( [0] => Array ( [0] => piklu [name] => piklu ) [1] => Array ( [0]          


        
相关标签:
4条回答
  • 2021-02-05 22:11

    file_put_contents writes a string to a file, not an array. http://php.net/manual/en/function.file-put-contents.php

    If you'd like to write what you see there in that print_r to a file, you can try this:

    ob_start();
    print_r($myarray);
    $output = ob_get_clean();
    file_put_contents("myfile.txt",$output);
    
    0 讨论(0)
  • 2021-02-05 22:11

    i m not sure but maybe its something like this. You want to serialize() the array on writting. it will put your array into test.txt

    file_put_contents('test.txt', serialize($array));
    
    0 讨论(0)
  • 2021-02-05 22:17

    Here are two ways:

    (1) Write a JSON representation of the array object to the file.

    $arr = array( [...] );
    file_put_contents( 'data.txt', json_encode( $arr ) );
    

    Then later...

    $data = file_get_contents( 'data.txt' );
    $arr = json_decode( $data, true );
    

    (2) Write a serialized representation of the array object to the file.

    $arr = array( [...] );
    file_put_contents( 'data.txt', serialize( $arr ) );
    

    Then later...

    $data = file_get_contents( 'data.txt' );
    $arr = unserialize( $data );
    

    I prefer JSON method, because it doesn't corrupt as easily as serialize. You can open up the data file and make edits to the contents, and it will encode/decode back without big headaches. Serialized data cannot be changed so easily or corrupted, or unserialize() won't work. Each variable is defined by type and length, and these values must be updated along with the actual change you are making.

    0 讨论(0)
  • 2021-02-05 22:24

    Your problem at the moment is basically that you're only able to write strings into a file. So in order to use file_put_contents you first need to convert your data to a string.

    For this specific use case there is a function called serialize which converts any PHP data type into a string (except resources).

    Here an example how to use this.

    $string_data = serialize($array);
    file_put_contents("your-file.txt", $string_data);
    

    You probably also want to extract your data later on. Simply use unserialize to convert the string data from the file back to an array.

    This is how you do it:

    $string_data = file_get_contents("your-file.txt");
    $array = unserialize($string_data);
    
    0 讨论(0)
提交回复
热议问题