转换为PHP 8.1后出现CSV导入问题

ecfdbz9o  于 2022-12-06  发布在  PHP
关注(0)|答案(1)|浏览(136)

我有下面的WordPress函数,在PHP 7中工作。因为转换到8.1,它不工作。

function dropdown_handler() {

$output = drop_function();
//send back text to replace shortcode in post
return $output;
}

function drop_function() {
//get the csv file with amounts
if ($file_handle = fopen("wp-content/plugins/drop/amounts.csv", "r")) {
while (!feof($file_handle) ) {
    $lines[] = fgetcsv($file_handle, 1024);
    
}
fclose($file_handle);
$lines = str_replace ("£","£",$lines);

}
else {
echo "Sorry, something went wrong";
}

在我的错误日志中,我看到“PHP警告:数组到字符串的转换在”中与$lines = str_replace行有关,但我认为fopen语句有问题。
基本上,单词Array被存储在$lines变量中,而不是CSV文件的内容中。

tyg4sfes

tyg4sfes1#

你的代码总是被破坏,只是破坏的方式比以前稍微明显一点...

$lines[] = fgetcsv($file_handle, 1024);

fgetcsv,除非失败,否则返回数组;然后将这个数组作为新项添加到另一个数组$lines中。结果是 * 数组的数组 *,如下所示:

$lines = [
    ['line 1 first item', 'line 1 second item'],
    ['line 2 first item', 'line 2 second item'],
];

然后,将整个数组传递给str_replace;但是str_replace只知道如何处理 * 一维 * 数组。
这是可行的:

$singleLine = ['line 1 first item', 'line 1 second item'];
var_dump(str_replace('item', 'ITEM', $singleLine));

但这并不能:

var_dump(str_replace('item', 'ITEM', $lines));

运行on multiple versions of PHP示例可以发现,在PHP 7.x下,str_replace的React只是保持内部数组不变--换句话说,它什么也没做。
在PHP 8中,它尝试将每个内部数组转换为字符串,发出警告并生成单词“Array”(然后将对其应用任何替换)。
两个PHP版本的修复是在每个内部数组上运行str_replace,最简单的方法是使用array_map

var_dump(
    array_map(
        fn($innerArray) => str_replace('item', 'ITEM', $innerArray),
        $lines
    )
);

或者,您可以完全删除str_replace行,因为当它实际上没有做任何事情时,您显然很高兴。

相关问题