views:

33

answers:

2

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);
A: 

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

Jonathan Kuhn
That's one solution I had already tried, but it doesn't work either. All I get is an empty csv file.
sassy_geekette
A: 

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

salathe