2

I am writing my first Wordpress Plugin that should simply write data to a csv file. This is the code, I can't figure out why the data won't write to the csv file?


add_action('admin_menu', 'myfirstplugin_admin_actions');
function myfirstplugin_admin_actions() {
add_options_page('MyFirstPlugin', 'MyFirstPlugin', 'manage_options', __FILE__, 'myfirstplugin_admin');
}

function myfirstplugin_admin()
{

$label = "Entries";

$entries = RGFormsModel::get_form_counts(1);
echo "The Form count for Form #1 is: ".$entries['total'].".";

$cvslabel = array ($label);
$cvsnumber = array ($entries);

$plugin_dir = plugin_dir_path( __FILE__ );
$logfile = $plugin_dir . 'data.csv';

$fp = fopen($logfile, 'w');

fwrite($fp, $cvslabel);
fwrite($fp, $cvsnumber);

fclose($fp);
}

Can someone explain to me why it won't work? And what i need to do so it will simply write the data to the csv file. I want the data to be dynamic so it will refresh the data in the csv file automatically.

1

Your Wordpress code is correct, the problem is the incorrect 2nd param to PHP's frwite(), which needs to be a string, and you're passing arrays.

I think you want something like:

fwrite ($fp, "$label\n") ;
fwrite ($fp, implode (',', array_keys ($entries)) . "\n") ;
fwrite ($fp, implode (',', array_values ($entries)) . "\n") ;
  • Also, if you add define('WP_DEBUG', true); to your wp-config.php (in you development environment, but not production) then you'll get PHP errors output to the browser, which would have helped you see that the problem was that you're passing arrays to fwrite() – Paul 'Sparrow Hawk' Biron Feb 20 '17 at 15:39
  • Thank you! It works just like I want indeed. The tip about define('WP_DEBUG', true); helps me a lot aswell. As you can see I'm pretty new to plugin development so i appreciate the help! – J.Bosma Feb 21 '17 at 8:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.