Search code examples
phpfopen

How to read a data-array saved in a text file and loop through them with PHP?


This values

//myfile.txt

data:[
  {'name': 'Item 1', 'icon': 'snowplow', 'inv': 'B123', 'eh': 'h'},
  {'name': 'Item 2', 'icon': 'snowplow', 'inv': 'B456', 'eh': 'h'},
  {'name': 'Item 3', 'icon': 'snowplow', 'inv': 'B789', 'eh': 'h'},
  {'name': 'Item 4', 'icon': 'snowplow', 'inv': 'B102', 'eh': 'h'}
]

are stored in a *.txt file that I can't change. If i read this textfile with PHP like this:

      $fn = fopen("myfile.txt","r");
      
      while(! feof($fn))  {
        $result = fgets($fn);
        
        // echo $result[name];
        // echo $result[icon];
        // echo $result[inv];
        // echo $result[eh];

      }

  fclose($fn);

How can i loop through this values with PHP?


Solution

  • As pointed out this task would be much simpler and less prone to failure if the source data were correctly formatted as a known data type such as JSON or even XML at a push. To fudge the above data so that it is easier to parse you need to remove the data: and change the single quotes for double quotes before continuing as you would normally. This is, it should be noted, a little hacky....

    /*
        replace the single quotes for double quotes
        then split the resulting string using `data:` as the delimiter
        and then convert to JSON
    */
    list( $junk, $data )=explode( 'data:', str_replace( "'", '"', file_get_contents('myfile.txt') ) );
    $json=json_decode( $data );
    
    
    foreach( $json as $obj ){
        /* 
            to get an unknown, potentially large, number of items from each object within data structure 
            you can iterate through the keys of the sub-object like this.
        */
        $keys=array_keys( get_object_vars( $obj ) );
        
        $tmp='';
        foreach( $keys as $key )$tmp.=sprintf( '%s=%s, ', $key, $obj->$key );
        printf('<div>%s</div>', $tmp );
        
        
        /* Or, with known items like this: */
        echo $obj->name . ' ' . $obj->icon . '/* etc */<br />';
    }