0

I am creating a array from a file:

$handle = fopen("inputfile.txt", "r");
if ($handle) {
    while (($str = fgets($handle)) !== false) {
           if (strlen($str) && $str[0] == '#') {
                    $pdate = substr($str, 1);
                    $date = rtrim($pdate);
                    $formatted = DateTime::createFromFormat('* M d H:i:s T Y',$date);
                }
                rtrim ($str, "\n");
                $exp = explode ('=', $str);
                if(count($exp) == 2){
                    $exp2 = explode('.', $exp[0]);  
                    if( count($exp2) == 2 ) {
                        if($exp2[1] == "dateTime"){
                            $s = str_replace("\\","",$exp[1]);
                            $d = strtotime($s);
                            $dateTime = date('Y-m-d H:i:s', $d);
                            $properties [$exp2[0]][$exp2[1]] = $dateTime;
                        } else {
                            $properties [$exp2[0]][$exp2[1]] = $exp[1];
                        }
                    } else {
                        $properties [$exp[0]] = $exp[1];
                    }
                } 
    }
    var_dump($properties); 
    fclose($handle);
} else {
    // error opening the file.
} 

var_dump($properties);

But in my result array there are always white spaces at the end of the values and I cannot get rid of them:

array(5) {
  ["folder"]=>
  array(5) {
    ["dateTime"]=>
    string(19) "2016-10-12 19:46:25"
    ["one"]=>
    string(47) "abc def
"
    ["two"]=>
    string(33) "ghi jk
"
    ["three"]=>
    string(150) "lm no
"
    ["four"]=>
    string(8) "pqr st
"
  }
}
peace_love
  • 6,229
  • 11
  • 69
  • 157

2 Answers2

6

You're missing to assign the result of rtrim ($str, "\n");. So your variable $str is not changed.

$str = rtrim($str, "\n");

Or, by default, to remove all whitespace characters (" \t\n\r\0\x0B"):

$str = rtrim($str);
Syscall
  • 19,327
  • 10
  • 37
  • 52
2

You can Use the rtrim() function to remove white spaces at beginning and end of your strings, but it is used one by one. You can also reffere to the response to this post : How can I trim all strings in an Array?

Tha says that you can use array_map and trim as this :

$result = array_map('rtrim', $source_array);

Angelure
  • 57
  • 7