1 Vote Vote

PHP, problem with str_replace while reading from array

Posted by topdog 562 days ago Questions| file html csv All

hello,

i am new to php, and i am trying to do a script that reads an CSV file(file1.csv) and compare the words in the file with words in a html file (file2.html), if word in file2.html match with the key part in file1.csv it should change the file2.html contents with the value of the key matched ..

what i have done so far is this :

$glossArray = array();
$file_handle = fopen("file1.csv", "r");
while (!feof($file_handle) ) {

    $line_of_text = fgetcsv($file_handle, 10000,';');
    $glossArray[$line_of_text[0]] =  $line_of_text[1];
    $counter++;
}
fclose($file_handle);

$file = file_get_contents("file2.html");

foreach($glossArray as $key => $value){
    $results = str_replace($key," means ".$value ,$file);
}

echo $results;

i think that my problem occurs when i try to iterate and change values .. because what i see is only the contents of file2.html unchanged

any help would be appreciated

thank you in advance

Nader

P.s. i edited the old code with the new one after your valuable advise .. now it's like this .. but still doesnt work.

Update: changing the foreach with :

$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);

solved the problem .. but another one comes up: now every time it replaces a string it adds the word 'Array' ahead of it.

Originally asked by: Nad on Stack Overflow

Discuss Bury


Who Voted for this Question