将 preg_match_all 匹配导出到 csv 文件

发布于 2024-09-26 01:35:50 字数 358 浏览 3 评论 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);

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半枫 2024-10-03 01:35:50

尝试:

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

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

第二个参数必须是一个数组。无需循环遍历匹配项(一个数组)并一次添加一个,只需传递整个匹配项数组 ($matches[0])

try:

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

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

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])

我偏爱纯白色 2024-10-03 01:35:50

在不知道字符串或正则表达式的结构的情况下,这只是一个猜测,但看起来您可能想要使用 PREG_SET_ORDER 来使 $matches 按匹配项对数组进行分组,而不是默认的 PREG_PATTERN_ORDER,默认的 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 文件的示例)。

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 default PREG_PATTERN_ORDER which groups the resulting array based on the capturing groups in the pattern (the documentation has examples).

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);
}

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文