0

我正在尝试将匹配项从 preg_match_all 导出到 csv 文件,但出现以下错误:

Warning: fputcsv() expects parameter 2 to be array, string given

这是我遇到问题的代码部分,如何修改它以便能够将匹配项导出到 csv 文件?

preg_match_all($pattern, $pos, $matches);

$fp = fopen('data.csv', 'w');
foreach($matches[0] as $data){  
 fputcsv($fp,$data);
}
fclose($fp);
4

2 回答 2

0

在不知道您的字符串或正则表达式的结构的情况下,这只是一个猜测,但看起来您可能希望使用匹配项PREG_SET_ORDER来使$matches数组分组,而不是默认PREG_PATTERN_ORDER的根据捕获组对结果数组进行分组在模式中(文档有示例)。

preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
    // Get rid of $match[0] (the overall match)
    unset($match[0]);
    // Write the captured groups to the CSV file
    fputcsv($fp, $match);
}

如果这不是您想要的,则需要您自己提供更多信息,例如$matches您想要的数组结构和/或输入 ( $subject) 和预期输出(CSV 文件的示例)。

于 2010-10-05T17:59:56.167 回答
0

尝试:

preg_match_all($pattern, $pos, $matches);

$fp = fopen('data.csv', 'w');
fputcsv($fp,$matches[0]);
fclose($fp);

第二个参数需要是一个数组。而不是遍历匹配项(一个数组)并一次添加一个,只需传递整个匹配项数组($matches[0]

于 2010-10-05T17:17:43.787 回答