• Добрый день.
    Пытаюсь экспортировать xls -файл при помощи библиотеки phpExcel в плагине вордпресса. Суть такова, что нужно запихнуть туда header-ы, и я их пытаюсь через add_action, т е мне надо как-то эти хедеры раньше разместить прежде чем они будут загружены админскими или т е раньше сформировать файл, только не выходит и привожу код:

    <form id="export_form" method="post" >
    			<p><input class="button-primary" name="exportfile" type="submit" value="Export XLS"></p>
    		</form>
    		<?php
    		if (isset($_POST['exportfile'])) {
    			$path_lib = plugin_dir_path(__FILE__);
    			error_reporting(E_ALL);
    			ini_set('display_errors', TRUE);
    			ini_set('display_startup_errors', TRUE);
    			date_default_timezone_set('Europe/London');
    			if (PHP_SAPI == 'cli') {
    				die('This example should only be run from a Web Browser'); }
    			require_once $path_lib . 'lib/Classes/PHPExcel.php';
    			$objPHPExcel = new PHPExcel();
    			$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
    				->setLastModifiedBy("Maarten Balliauw")
    				->setTitle("Office 2007 XLSX Test Document")
    				->setSubject("Office 2007 XLSX Test Document")
    				->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
    				->setKeywords("office 2007 openxml php")
    				->setCategory("Test result file");
    			$objPHPExcel->setActiveSheetIndex(0)
    				->setCellValue('A1', 'Hello')
    				->setCellValue('B2', 'world!')
    				->setCellValue('C1', 'Hello')
    				->setCellValue('D2', 'world!');
    			$objPHPExcel->setActiveSheetIndex(0)
    				->setCellValue('A4', 'Miscellaneous glyphs')
    				->setCellValue('A5', 'asdfdsafas');
    			$objPHPExcel->getActiveSheet()->setTitle('Simple');
    			$objPHPExcel->setActiveSheetIndex(0);
    			header('Content-Type:  application/vnd.ms-excel');
    			header('Content-Disposition: attachment;filename="1434.xls"');
    			header('Cache-Control: max-age=0');
    			$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    			$writer->save('1434.xls');
    			exit;
    		}

    при таком коде вываливаются ошибки,

    [Tue Jan 08 08:21:14 2013] [error] [client 127.0.0.1] PHP Warning:  Cannot modify header information - headers already sent by (output started at /home/ss/www/wpsite/httpdocs/wp-admin/menu-header.php:161) in /home/ss/www/wpsite/httpdocs/wp-content/plugins/cf_update/soundst-update-custom-fields.php on line 231, referer: http://wpsite.dev/wp-admin/options-general.php?page=cf_update
    [Tue Jan 08 08:21:14 2013] [error] [client 127.0.0.1] PHP Warning:  Cannot modify header information - headers already sent by (output started at /home/ss/www/wpsite/httpdocs/wp-admin/menu-header.php:161) in /home/ss/www/wpsite/httpdocs/wp-content/plugins/cf_update/soundst-update-custom-fields.php on line 232, referer: http://wpsite.dev/wp-admin/options-general.php?page=cf_update
    [Tue Jan 08 08:21:14 2013] [error] [client 127.0.0.1] PHP Warning:  Cannot modify header information - headers already sent by (output started at /home/ss/www/wpnew/httpdocs/wp-admin/menu-header.php:161) in /home/ss/www/wpsite/httpdocs/wp-content/plugins/cf_update/soundst-update-custom-fields.php on line 233, referer: http://wpsite.dev/wp-admin/options-general.php?page=cf_update

    Но это понятно, далее делаю по-иному: — весь функционал(формирование файла xls) переношу в отдельную функцию и вешаю ее на админский action:

    <form id="export_form" method="post" >
    			<p><input class="button-primary" name="exportfile" type="submit" value="Export XLS"></p>
    		</form>
    		<?php
    		if (isset($_POST['exportfile'])) {
    			add_action('admin_init', 'xls_download');
    		}
    		?>
    
    function xls_download() {
    	$path_lib = plugin_dir_path(__FILE__);
    	error_reporting(E_ALL);
    	ini_set('display_errors', TRUE);
    	ini_set('display_startup_errors', TRUE);
    	date_default_timezone_set('Europe/London');
    	if (PHP_SAPI == 'cli') {
    		die('This example should only be run from a Web Browser'); }
    		require_once $path_lib . 'lib/Classes/PHPExcel.php';
    		$objPHPExcel = new PHPExcel();
    		$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
    		->setLastModifiedBy("Maarten Balliauw")
    		->setTitle("Office 2007 XLSX Test Document")
    		->setSubject("Office 2007 XLSX Test Document")
    		->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
    		->setKeywords("office 2007 openxml php")
    		->setCategory("Test result file");
    		$objPHPExcel->setActiveSheetIndex(0)
    		->setCellValue('A1', 'Hello')
    		->setCellValue('B2', 'world!')
    		->setCellValue('C1', 'Hello')
    		->setCellValue('D2', 'world!');
    		$objPHPExcel->setActiveSheetIndex(0)
    		->setCellValue('A4', 'Miscellaneous glyphs')
    		->setCellValue('A5', 'asdfdsafas');
    		$objPHPExcel->getActiveSheet()->setTitle('Simple');
    		$objPHPExcel->setActiveSheetIndex(0);
    		header('Content-Type:  application/vnd.ms-excel');
    		header('Content-Disposition: attachment;filename="1434.xls"');
    		header('Cache-Control: max-age=0');
    		$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    		$writer->save('1434.xls');
    		die();
    }

    Ну и в функции ставлю die(). Тут ошибок никаких не вывешивается в лог и файл не загружается. И вообще даже если пытаюсь Print_r разместить там, ничего не выходит. Перевешал уже и на admin_head и на init — не помогает. И приоритеты уже менял.
    Прошу навести наверный шаг или подсказать где бок. Спасибо.

Просмотр 2 ответов — с 1 по 2 (всего 2)
  • Модератор Юрій

    (@yube)

    По первому коду: выводите хедеры после «текста» (как минимум, после <form...) — вот и ошибка.

    По второму: навешивание чего бы то ни было на хук, который уже выполнен задолго до того, как «дойдет ход», т.е. начнет выводится форма, просто бессмысленно. Цеплять обработчик надо прямо в «теле» плагина, а не внутри функции вывода страницы админки (форма ж там, я правильно понял?)

    поставил я вывод выше <from>, все равно те же варнинги выводятся и ничего не выходит — не загружается.
    Мне кажется что дело в правильном крючке.

Просмотр 2 ответов — с 1 по 2 (всего 2)
  • Тема «Добавление Header-ов при нажатии кнопки в плагине» закрыта для новых ответов.