Results 1 to 2 of 2
  1. #1
    Join Date
    Dec 2003
    Posts
    23

    Unanswered: reading text file to an associative array

    i have a text file in this format and would like to read it into an associative array. How would I do this? Or is there a better way to do this?

    key1
    value1
    key2
    value2
    key3
    value3

    $array['key1'] = value1
    $array['key2'] = value2
    $array['key3] = value3

    here is what I have so far

    Code:
    $file = fopen("$DOCUMENT_ROOT/file.txt", "r");
    
    while (!feof($file))
    {
    	$array[fgets($file,99)]  = fgets($file, 999);
    }
    fclose($file);
    echo $array['key1'];

  2. #2
    Join Date
    Dec 2003
    Posts
    23
    Ok, I've change the format of the file a little bit. But I'm still not able to read the text file into the array like I want to. Please let me know what could be wrong with this code. Thanks

    key1, value1
    key2, value2
    key2, value2

    Code:
    <?php
    $count = 0;
    $file = fopen("$DOCUMENT_ROOT/iapp/iappsites.txt", "r");
    while (!feof($file))
    {
    	$cur_line = fgets($file, 100);
    	if (strlen($cur_line) > 1)
    	{
    		list($key, $value) = split (',', $cur_line);
    		trim($key);
    		trim($value);
    		
    		$url[$count] = array("$key" => $value);
    		$count += 1;
    	} //end if 
    }
    fclose($file);
    echo $url['key1'];
    
    ?>

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •