Austin Mauldin Austin Mauldin - 1 year ago 68
PHP Question

Better way to do a str_replace on csv value

I'm trying to look for a degree character in uploaded csv's before they are hitting my output method. As I'm writing how I would normally do this I feel like my solution will involve way more steps than it should. So, **I'm asking is there a better way to look for a

symbol in a csv file and replace it with
. Here's what the approach I'm currently taking:

$file = get_attached_file( $csv_file ); //set file_path
$file_array = array(); //declare an array so it gets key and values approriately
$array_key = 'angle'; //define where the degree symbol is to be added
$file_array = str_getcsv(file_get_contents($file));
if( array_key_exists($array_key, $file_array) ) {
foreach ($file_array as $key => $value) {
$degree = '°';
$replace = '&#176';
$value = str_replace($degree, $replace, $value);

My problem is, wouldn't I then have to loop through each value in the array, put it back in a csv which would then require me to define what columns need to be outputted when some files won't have the
column I'm trying to replace in the first place.

Also, will php be able to find and decode the

Answer Source

If replacing the degree symbol is the only thing which concerns you then this is going to be more efficient from a micro-optimization standpoint because you can skip calling the foreach(){} loop and only need to call str_replace() one time:

$file_array = str_getcsv(str_replace('°', '°', file_get_contents($file)));

Update per the comments:

// Read the CSV file into a PHP variable as a string
// Replace all ° with °
// Overwrite the original file with the new string
file_put_contents($file, str_replace('°', '°', file_get_contents($file)));