PHP - parsing a txt file

后端 未结 9 1764
余生分开走
余生分开走 2020-11-29 18:43

I have a .txt file that has the following details:

ID^NAME^DESCRIPTION^IMAGES
123^test^Some text goes here^image_1.jpg,image_2.jpg
133^hello^some other test^         


        
相关标签:
9条回答
  • 2020-11-29 19:07

    My solution

    function parseTextFile($file){
        if( !$file = file_get_contents($file))
            throw new Exception('No file was found!!');
        $data = [];
        $firstLine = true;
        foreach(explode("\n", $file) as $line) {
            if($firstLine) { 
                $keys=explode('^', $line);
                $firstLine = false; 
                continue; 
            } // skip first line
            $texts = explode('^', $line);
            $data[] = array_combine($keys,$texts);
        }
        return $data;
    }
    
    0 讨论(0)
  • 2020-11-29 19:12

    Try fgetcsv() with ^ as the separator character:

    $file = fopen($txt_file,"r");
    print_r(fgetcsv($file, '^'));
    fclose($file);
    

    http://www.w3schools.com/php/func_filesystem_fgetcsv.asp

    0 讨论(0)
  • 2020-11-29 19:15

    youse a list, and split the "image_1.jpg,image_2.jpg" after you explode the string:

    list($number, $status, $text, $images) = explode("^", $data);
    
    $splited_images= preg_split(',', $images);
    
    0 讨论(0)
  • I would like to contribute a file that provides atomic data structures.

    $lines = file('some.txt');
    $keys = explode('^', array_shift($lines));
    $results = array_map(
        function($x) use ($keys){
            return array_combine($keys, explode('^', trim($x)));
        }, 
        $lines
    );
    
    0 讨论(0)
  • 2020-11-29 19:21

    Ok, didn't see the edited version, so here's a redo. It's most likely a CSV file that uses carets as the separator, so...

    $fh = fopen('yourfile.txt');
    $headers = fgetcsv($fh, 0, '^');
    $details = array();
    while($line = fgetcsv($fh, 0, '^')) {
       $details[] = $line;
    }
    fclose($fh);
    
    0 讨论(0)
  • 2020-11-29 19:23
    <?php
    $row = 1;
    if (($handle = fopen("test.txt", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, "^")) !== FALSE) {
            $num = count($data);
            echo "<p> $num fields in line $row: <br /></p>\n";
            $row++;
            for ($c=0; $c < $num; $c++) {
                echo $data[$c] . "<br />\n";
            }
        }
        fclose($handle);
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题