1

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?

1
  • 2
    Have you really, definitely got no control over this data format? Because it's JSON-like, but not actually JSON. If you just store proper JSON then the problem will be trivial to solve. As it is, you need to write a custom parser, which really isn't trivial. Or maybe whoever created this format can give you some code, since they presumably have a way to parse it. Commented Dec 17, 2021 at 11:31

1 Answer 1

2

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 />';
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.