将 preg_match_all 匹配导出到 csv 文件
我正在尝试将匹配项从 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);
I'm trying to export matches from preg_match_all to a csv file but am getting the following error:
Warning: fputcsv() expects parameter 2 to be array, string given
This is the section of code I'm having issues with, how can I modify it so I am able to export the matches to a csv file?
preg_match_all($pattern, $pos, $matches);
$fp = fopen('data.csv', 'w');
foreach($matches[0] as $data){
fputcsv($fp,$data);
}
fclose($fp);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试:
第二个参数必须是一个数组。无需循环遍历匹配项(一个数组)并一次添加一个,只需传递整个匹配项数组 (
$matches[0]
)try:
The second argument needs to be an array. instead of looping through the matches (an array) and adding them one at a time, just pass the entire matches array (
$matches[0]
)在不知道字符串或正则表达式的结构的情况下,这只是一个猜测,但看起来您可能想要使用
PREG_SET_ORDER
来使$matches
按匹配项对数组进行分组,而不是默认的PREG_PATTERN_ORDER
,默认的PREG_PATTERN_ORDER
根据模式中的捕获组对结果数组进行分组(文档 有示例)。如果这不是您想要的,则需要您自己提供更多信息,例如您想要的
$matches
数组的结构和/或输入 ($subject
)和预期输出(CSV 文件的示例)。Without knowing the structure of your string or the regular expression, this is just a guess but it looks like you may be wanting to use
PREG_SET_ORDER
to make the$matches
array group by the matches, rather than the defaultPREG_PATTERN_ORDER
which groups the resulting array based on the capturing groups in the pattern (the documentation has examples).If that is not what you're after, more info is needed from yourself like the structure of the
$matches
array that you want, and/or the input ($subject
) and expected output (an example of the CSV file).