Can u pls tell me how to bind multiple images in powerpoint using php powerpoint library? In the below code i used foreach loop to add multiple images in powerpoint but only one image is adding so pls help me.
<?php
require_once("db_config.php");
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
include 'PHPPowerPoint.php';
include 'PHPPowerPoint/IOFactory.php';
?>
<html>
<h3 align="center">Welcome <?php echo $_SESSION['user_name'];?>
<br>
Logout
</h3>
<body>
<?php
echo "<div align='center'>";
echo "<form method='post' action=''>";
echo "<table align='center' border='1'>
<tr>
<th></th>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>UserName</th>
</tr>";
$result = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><input type='checkbox' name='user_id[]' value='".$row['user_id']."' /> </td>";
echo "<td>" . $row['user_id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['user_name'] . "</td>";
echo "</tr>";
}
echo "</table><br>";
echo "<input type='submit' name='submit' value='Export PPT' />";
echo "</form></div>";
?>
</body>
</html>
<?php
if(isset($_POST['submit']) && isset($_POST['user_id'])){
$user_id = $_POST['user_id'];
foreach($user_id as $selected){
echo $selected."</br>";
$result = mysql_query("SELECT * FROM users WHERE user_id ='".$selected."'");
$row = mysql_fetch_array($result);
$img = '<img src="images/'.$row["image_name"].'" height="200" width="300" />';
$objPHPPowerPoint = new PHPPowerPoint();
// block sets slide logo.
$currentSlide = $objPHPPowerPoint->getActiveSlide();
$shape = $currentSlide->createDrawingShape();
$shape->setPath('images/'.$row["image_name"]);
$shape->setWidth(640);
$shape->setHeight(480);
$shape->setOffsetX(10);
$shape->setOffsetY(10);
// block sets text for first slide.
$shape = $currentSlide->createRichTextShape();
$shape->setHeight(700);
$shape->setWidth(600);
$shape->setOffsetX(10);
$shape->setOffsetY(500);
$shape->getAlignment()->setHorizontal( PHPPowerPoint_Style_Alignment::HORIZONTAL_CENTER );
$textRun = $shape->createTextRun('FirstName:'.$row["first_name"].' Lastname:'.$row["last_name"].' UserName:'.$row["user_name"]);
$textRun->getFont()->setBold(true);
$textRun->getFont()->setSize(30);
$textRun->getFont()->setColor( new PHPPowerPoint_Style_Color( '#FFFF' ) );
// block sets text for first slide ends.
$filename = str_replace('.php', '.pptx', __FILE__);
$newname = "PresentationReport-" . date('Y-m-d-H-i-s') . ".pptx";
$objWriter = PHPPowerPoint_IOFactory::createWriter($objPHPPowerPoint, 'PowerPoint2007');
$objWriter->save(str_replace('.php', '.pptx', __FILE__));
// block to download file.
header("Pragma: no-cache");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=" . $newname);
ob_clean();
flush();
readfile($filename);
exit();
}
}
else
{
echo "<div align='center'>Please choose the user</div>";
exit;
}
?>
How can i add multiple images using php powerpoint library?
Two troubles can be indentified in your snippet:
1 - You're calling "new Powerpoint" to each element in foreach, and due this
you always override the previous slide.
2 - You're positioning your shapes in the same x/y offset:
$shape->setOffsetX(10);
$shape->setOffsetY(10);
So in the foreach all shapes will be stacked.
To a functional solution you'll need to mount a valid algorithm like:
I'll have 4 photos by slide for example so:
$resultsFromDataBase = $resultsFromDataBase;
// Array chunk to create a "logic" 4 photos ... jump to the new slide
$resultsBySlide = array_chunk($resultsFromDataBase, 4);
// Each photo needs your independent X offset
// Note the fake values, you need to calculate them
$positionsByIndex = [
0 => 10,
1 => 20,
2 => 30,
3 => 40
];
foreach ($resultsBySlide as $i => $rows) {
// 4 photos -> Jump the slide and create another one
$ppt->createSlide();
// SlideCount -1 gets your current index
$slideIndex = $ppt->getSlideCount()-1;
$currentSlide = $objPHPPowerPoint->getActiveSlide();
foreach ($rows as $position => $row) {
$shape = $currentSlide->createDrawingShape();
$shape->setPath('images/'.$row["image_name"]);
$shape->setWidth(640);
$shape->setHeight(480);
$shape->setOffsetX($positionsByIndex[$position]); // Here the point
$shape->setOffsetY(10);
}
}
And the last point but not less important: Don't use mysql_* in your project
use: PDO or mysqli_* instead
Related
I need to attach two tables.
First loop is perfect,
but second For-loop table goes to the Bottom.
I need to attach that bottom table to that previous one.
Can anyone please solve this problem?
Any Solution would be appreciated, so suggest something to solve this.
<?php
include 'pappu.php';
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
$grab=ngegrab('https://www.cryptopia.co.nz/api/GetMarkets/USDT');
$json = json_decode($grab, true);
$usd= $json['Data'][3]['AskPrice'];
$grabb=ngegrab('https://www.cryptopia.co.nz/api/GetMarkets/USDT');
$jsonss = json_decode($grabb, true);
$dogeusd= $jsonss['Data'][8]['AskPrice'];
$grabsz=ngegrab('https://www.cryptopia.co.nz/api/GetMarkets/DOGE');
$jsonsz = json_decode($grabsz);
$grabs=ngegrab('https://www.cryptopia.co.nz/api/GetMarkets/BTC');
$jsons = json_decode($grabs);
echo "<table border=1>";
echo "<th>BTC EXCHANGE</th>";
if($jsons)
foreach ($jsons->Data as $sam){
$market= $sam->Label . "\n";
$link= $sam->AskPrice . "\n";
echo "<tr><td>$market</td>";
$link = number_format($link, 8);
echo "<td>$link" ;
echo '($';
echo number_format($link * $usd, 6) ;
echo ')';
echo "</td></tr>";
}
echo "<th>DOGE EXCHANGE</th>";
foreach ($jsonsz->Data as $sam){
$market= $sam->Label . "\n";
$link= $sam->AskPrice . "\n";
echo "<tr><td>$market</td>";
$link = number_format($link, 8);
echo "<td>$link" ;
echo '($' ;
echo number_format($link * $dogeusd, 6) ;
echo ')';
echo "</td></tr>";
}
echo "</table>";
?>
First set the table headers (<th>), then set the table body if you want all the headers to appear inline.
You can then make arrays for the rows of the two tables and just output for each row.
Note: In case your $btc and $doge arrays have a different amount of rows or are not in the same order you then might have to create a third array by combining the two, then loop over that.
echo '<table border="1">
<tr>
<th colspan="2">BTC EXCHANGE</th>
<th colspan="2">DOGE EXCHANGE</th>
</tr>';
// prepare the rows
$btc = array();
$doge = array();
if($jsons)
{
foreach ($jsons->Data as $sam)
{
$number = (float) $sam->AskPrice;
array_push($btc, array($sam->Label, number_format($number,8) ));
}
foreach ($jsonsz->Data as $sam)
{
$number = (float) $sam->AskPrice;
array_push($doge, array($sam->Label, number_format($number,8) ));
}
// assuming count($btc) and count($doge) are the same
for($i=0; $i< count($btc); $i++)
{
echo '<tr>
<td>'.$btc[i][0].'</td>
<td>'.$btc[i][1].' ($'.number_format($btc[i][1] * $usd, 6).')</td>
<td>'.$doge[i][0].'</td>
<td>'.$doge[i][1].' ($'.number_format($doge[i][1] * $usd, 6).')</td>
</tr>';
}
}
echo '</table>';
?>
You have two <th> cells which should be in a table row <tr>:
echo "<th>BTC EXCHANGE</th>";
and
echo "<th>DOGE EXCHANGE</th>";
Change your code to:
echo "<tr><th>BTC EXCHANGE</th></tr>";
and
echo "<tr><th>DOGE EXCHANGE</th>";
I'm creating a PHP web application in combination with SQL to order stuff. I'm randomly generating textboxes based on the amount of records I have. I want to pass the individual values to insert to the database. I want each cell to have a textbox in which I can input values and pass them with that cell. So if I want to order 2 of cell one I want to pass that value into a database.
Here's the code:
$i = 0;
if ($AanbodsTabel === false){
die(mysql_error());
}
while ($row = mysqli_fetch_array($AanbodsTabel)){
echo "<tr><td width = 4%>". htmlentities($row['Fustcode']) . "</td>";
echo "<td width = 8%>" . htmlentities($row['cultivar']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalFust']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalPerFust']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalStelen']) . "</td>";
echo "<td width = 4%><input type ='text' id='Bestelbox' value='' name='AantalBestellen".$i."'></td>";
echo "<td width = 6%>" . htmlentities($row['AantalFustBesteld']) . "</td>";
echo "<td width = 6%>" . htmlentities($row['AantalStelenBesteld']) . "</td>";
135: echo '<td width = 8%><a href="Home.php?aanbodid='. htmlentities($row['aanbodid']) .'&hoeveelheid='. $_GET["AantalBestellen$i"]. '"'
. ' class = "btnBestel">Bestel</a></td></tr>';
$i = $i + 1;
}
The error I'm getting is undefined index. I guess this is because the name isn't unique. But whatever I do I still get the error.
I'm getting:
undefined index: AantalBestellen0 on line 135;
you can use javascript for example
note i will bold the code you need, the rest is context.
note this is from a similar project of mine but you should get the point.
<div id="meldingen_top_div">
<?php
echo "<div class='alert_Top_Div_Left_Outer'>
<input type='submit' value='Openstaande Meldingen' class='btnLoad' name='' onclick='toggleThis(" . '"' . "#meldTableTop" . '"' . "), toggleThis(".'"'.".alert_Top_Div_Left_Inner".'"'.")'/>
<div class='alert_Top_Div_Left_Inner'>
<table class='tableRed' id='meldTableTop'><caption/><thead/><tfoot/><tbody>";
$sqlVII = "SELECT Meldingen.Melding_id, FORMAT(Meldingen.Melding_datum, 'dd-mM-yyyy') AS Melding_datum, Producten.Product_naam, Leveranciers.Leverancier_naam, Meldingen.Melding_notitie
FROM MovieWorld.dbo.Producten,
MovieWorld.dbo.Meldingen,
MovieWorld.dbo.Categorieen,
MovieWorld.dbo.Leveranciers
WHERE Producten.Product_id = Meldingen.Product_id AND Producten.Categorie_id = Categorieen.Categorie_id AND Categorieen.Leverancier_id = Leveranciers.Leverancier_id AND Producten.Product_actief = 1 AND Meldingen.Melding_actief = 1
";
$resV= $db->executeQuery($sqlVII);
$i=1;
if($resV!=FALSE){
while($arrx = sqlsrv_fetch_array($resV)){
Code wich is relevant for you:
echo "<tr>
<td><p class='meldDate'>{$arrx['Melding_datum']}</p></td>
<td>{$arrx['Product_naam']}</td>
<td>{$arrx['Leverancier_naam']}</td>
<td><input id='txt{$i} type='text' name='thisdoesntevenmatter' value='..'/></td>
<td><img src='somerandompath.png' onclick='getTxt(".'"txt{$i}"'.")'/></td>
</tr>"
$i=$i+1;
}
}else{}echo '</tbody></table></div></div>';
?>
</div>
and the Javascript function
function getTxt(id){
var tempId = document.getElementById(id).value;
return tempId;
}
however.. you can also send the value back into a php variable, OR use AJAX to pass it to an PHP class to insert it into the Database.
edit
Your quotes in line 135: seem incorrect. try this:
echo '<td width = 8%><a href="Home.php?aanbodid={htmlentities($row['aanbodid']) }&hoeveelheid={$_GET['AantalBestellen$i']}"'
. ' class = "btnBestel">Bestel</a></td></tr>';
Where you get undefined index? on that $_POST['AantalBestellen'] ?
Use
if (isset($_POST['AantalBestellen'])) { }
to identify that the post value has been set
same do later for the hoeveelheid:
if (isset($_GET['hoeveelheid'])) { }
echo-ing the input field:
echo "<td width = 4%><input type ='text' id='Bestelbox' value='" . $_GET['hoeveelheid'] . "' name='AantalBestellen'></td>";
Also, dont forget to clear the spaces in:
'&hoeveelheid = '. $_POST //near the =
I'm trying to display image in 5 by 3 table.
I'm able to display the images if all empty(blank.png).
Here is the code
<?PHP
$ds ='\image';
$imagefile = array("EX_W1_01.png", "EX_W1_02.png", "EX_W2_01.png","EX_W3_01.png");
echo "<pre>"; print_r($imagefile);
$file = 'blank.png';
$d = $ds.$file;
echo "<table border = 1 width=\"540px\" cellspacing=\"0px\" cellpadding=\"0px\">";
for($row=1;$row<=5;$row++){
echo "<tr>";
for($col=1;$col<=3;$col++){
// echo"<td height=60px>W$row</td>";
//if()
echo"<td height=60px>W$row<img border = 1 height = 120 width = 120 src = $d ></td>" .PHP_EOL;
}
echo "</tr>";
}
echo "</table>";
?>
I want to display the images base on middle file name array $imagefile eg W1, W2 and if not in array, I will display the blank.png.
I was able to get the middle file name by this code, but I cannot display the images in correct row/col.
for($i=0;$i<count($imagefile); $i++) {
$wd = substr($imagefile[$i], 3, strpos($imagefile[$i], '_'));
}
Can you try this,
Based on your code add these when you echo the image,
$wd = substr($imagefile[$i], 3, strpos($imagefile[$i], '_'));
if($wd == *the increment either row or col*)
{
echo"<td height=60px>W$row<img border = 1 height = 120 width = 120 src = $d ></td>" .PHP_EOL;
}
else
{
echo"<td height=60px>No image</td>" .PHP_EOL;
}
See if it works.
Here it is
<?php
$ds ='/image';
$imagefile = array("EX_W1_01.png", "EX_W1_02.png", "EX_W2_01.png","EX_W3_01.png");
//echo "<pre>"; print_r($imagefile);
$default = 'blank.png';
?>
<table border = 1 width=\"540px\" cellspacing=\"0px\" cellpadding=\"0px\">
<?php
for($row=1;$row<=5;$row++){
?>
<tr>
<?php
for($col=1;$col<=3;$col++){
// construct the file name
$filename = 'EX_W' . $row . '_0' . $col . '.png';
// set the default image file
$imgPath = $ds . '/' . $default;
// in case the file name exists in your array with images,
// set the correct path to the image
if (in_array($filename, $imagefile)) {
$imgPath = $ds . '/' . $filename;
}
?>
<td height=60px>
<img border="1" height="120" width="120" src="<?php echo $imgPath; ?>"/>
</td>
<?php } ?>
</tr>
<?php
}
?>
</table>
As you can see I also prefer to "embed" the php code in the HTML. It makes no sense to me outputting HTML code through the PHP engine if it can be parsed as is ;-)
I have question referring to the session in PHP.
I've coded in PHP for setting the session and I want to delete it , but I got some errors and confusing with using the UNSET(variable $_SESSION). Perhaps anyone could help me to show what should I do with this matter. Thanks in advance
$_SESSION['chart'] = array();
$_SESSION['chart'][0]['index'] = 0
$_SESSION['chart'][0]['type'] = $type;
$_SESSION['chart'][0]['idanimal'] = $iddog;
$_SESSION['chart'][0]['price'] = $price;
printdata(); // <== this is the function to print out the data
All I want to do is just delete based on the index in this session
Here's the function :
function printdata()
{
$totalharga = 0;
if(is_array($_SESSION['chart']))
{
echo "<h3>"."Berikut adalah keranjang belanja anda" . "</h3>". "<br>";
$max = count($_SESSION['chart']);
$th1 = "<th>" . "No" . "</th>";
$th2 = "<th>" . "Animal Type" . "</th>";
$th3 = "<th>" . "ID Binatang" . "</th>";
$th4 = "<th>" . "Harga" . "</th>";
$th5 = "<th>" . "Hapus Data" . "</th>";
echo "<table border=1>";
echo "<tr>";
echo $th1 ;
echo $th2;
echo $th3;
echo $th4;
echo $th5;
echo "</tr>";
for ($indexo = 0; $indexo < $max; $indexo++)
{
echo "<tr>";
echo "<td>" . $indexo."</td>";
echo "<td>" . $_SESSION['chart'][$indexo]['type']."</td>";
echo "<td>" . $_SESSION['chart'][$indexo]['idanimal']."</td>";
echo "<td>" . "Rp. " . $_SESSION['chart'][$indexo]['harga']. ",-" ."</td>";
echo "<td>" . "<a href='deletesession.php?session=$indexo'>" ."Proses ". "</a>"."</td>";
$totalharga += $_SESSION['chart'][$indexo]['harga'];
echo "</tr>";
}
echo "</table>" . "<br/>";
echo "<blockquote>" . "Total Pembelian Item Yang Anda Pesan =". "<h2>". "Rp." . $totalharga . ",-" ."</h2>" . "</blockquote>";
}else
{
echo "Chart is still Empty";
}
}
I've already tried this :
Suppose that there is a chart already filled by the contents then I tried to delete within this code, I've received error with the unset variable
unset($_SESSION['chart'][1])
Thank you
I spot several things that could be improved in your code:
Don't echo in your functions, return instead (then echo what the function returns). This gives you more flexibility regarding what you do with your result.
PHP has a built-in loop for iterating arrays, the foreach loop. You should be using that instead of for.
So here's what I have:
function print_session_data($session) {
if (!is_array($session)) {
return "Array is empty";
}
$table_data = "";
$total_harga = 0;
foreach ($session as $index => $data) {
$table_data .= <<<TABLE_DATA
<tr>
<td>$index</td>
<td>{$data["type"]}</td>
<td>{$data["idanimal"]}</td>
<td>Rp. {$data["harga"]}</td>
<td>Proses</td>
</tr>
TABLE_DATA;
$total_harga += $data["harga"];
}
$result = <<<RESULT
<h3>Berikut abalah keranjang belanja anda</h3>
<table border="1">
<thead>
<tr>
<th>No</th>
<th>Animal Type</th>
<th>ID Binatang</th>
<th>Harga</th>
<th>Hapus Data</th>
</tr>
</thead>
<tbody>
$table_data
</tbody>
</table>
<blockquote>Total Pembelian Item Yang Anda Pesan = <strong>Rp. $total_harga</strong></blockquote>
RESULT;
return $result;
}
$_SESSION['chart'] = array();
$_SESSION['chart'][0]['type'] = "Type";
$_SESSION['chart'][0]['idanimal'] = 6;
$_SESSION['chart'][0]['price'] = '$25';
$_SESSION['chart'][0]['harga'] = 25;
echo print_session_data($_SESSION["chart"]); // <== this is the function to print out the data
Suppose that there is a chart already filled by the contents then I
tried to delete within this code, I've received error with the unset
variable unset($_SESSION['chart'][1])
From what I can see from your code the best way to unset the data correctly is as follow:
DEMO.
You have to check if the $_SESSION['chart'][0] was set before using the session variable index again. If it $_SESSION['chart'] array still contains other indexes then you can call printdata(); else indicate that the session was empty.
My goal here is to have the browser download a csv file using headers to do it. For some reason yet to be determined, the browser seems to be downloading the HTML content of the current page (and not the contents of the array I've given it).
Here is the code I've been using:
$arr1 = array(array("1","2","3","4"),array("2","1","6","6"));
$tmp_handle = fopen('php://memory', 'r+');
fputcsv($tmp_handle, $arr1);
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
rewind($tmp_handle);
echo stream_get_contents($tmp_handle);
I've followed the instructions of many articles / SO questions I've read and I don't see what's wrong with this code.
I of course appreciate any help that I can get here!
Here is the complete code (upon request):
<?php
global $wpdb;
// Get total number of active referrers
$referrer_check = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."referrer");
$num_of_referrers = 0;
foreach ( $referrer_check as $check)
{
$num_of_referrers++;
}
// Get total number of referral transactions
$num_of_referrals = 0;
$num_referral_check = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."referrer_transactions");
foreach ( $num_referral_check as $check)
{
$num_of_referrals++;
}
// Check for the top referrer
$top_referrer = $wpdb->get_row("SELECT referrer_id, count(*) as row_count FROM ".$wpdb->prefix."referrer_transactions GROUP BY referrer_id ORDER BY COUNT(*) DESC");
$top_referrer_result = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."referrer WHERE referrer_id = $top_referrer->referrer_id");
// Construct the table
// Create array for second table
$ref_transactions_table_arr = array(
array("Referee Name", "Referee ID", "Referee Sign Up", "Referee Email","Referrer ID","Referrer Name"));
foreach ($num_referral_check as $check)
{
$ref_transactions_table_arr[] = array(
$wpdb->get_var("SELECT billing_name FROM ".$wpdb->prefix."pmpro_membership_orders WHERE user_id = $check->buyer_id"),
$check->buyer_id,
$wpdb->get_var("SELECT user_registered FROM ".$wpdb->prefix."users WHERE ID = $check->buyer_id"),
$wpdb->get_var("SELECT user_email FROM ".$wpdb->prefix."users WHERE ID = $check->buyer_id"),
$wpdb->get_var("SELECT referrer_id FROM ".$wpdb->prefix."referrer WHERE referrer_id = $check->referrer_id"),
$wpdb->get_var("SELECT referrer_name FROM ".$wpdb->prefix."referrer WHERE referrer_id = $check->referrer_id")
);
}
// Create array for first table
$active_ref_table_arr = array(
array('Referrer Name', 'Referrer ID', '# of Referrals', 'Address','Referrer Email','Lifetime Referrals'));
foreach ( $referrer_check as $check)
{
$active_ref_table_arr[] = array(
$check->referrer_name,
$check->referrer_id,
$wpdb->get_var("SELECT count(*) FROM ".$wpdb->prefix."referrer_transactions WHERE referrer_id = $check->referrer_id"),
$check->referrer_street . " " . $check->referrer_city . ", " . $check->referrer_state . " " . $check->referrer_zip,
$wpdb->get_var("SELECT user_email FROM ".$wpdb->prefix."users WHERE ID= $check->referrer_id"),
$wpdb->get_var("SELECT count(*) FROM ".$wpdb->prefix."referrer_transactions WHERE referrer_id = $check->referrer_id")
);
}
// Download file
if(isset($_POST['export_tbl_one']))
{
$csvData = array(
array("1","2","3","4"),
array("2","1","6","6")
);
$fp = fopen('php://memory', 'w+');
/*foreach ($csvData as $row) {
fputcsv($fp, $row);
}*/
fputcsv($fp,$csvData);
rewind($fp);
$csvFile = stream_get_contents($fp);
fclose($fp);
header('Content-Type: text/csv');
header('Content-Length: '.strlen($csvFile));
header('Content-Disposition: attachment; filename="file.csv"');
exit($csvFile);
}
?>
<div class="nav">
<ul>
<li class="first">Total Referrers: <? echo $num_of_referrers; ?></li>
<li>Total Referals: <? echo $num_of_referrals; ?></li>
<li>Top Referrer: <? echo $top_referrer->referrer_id . ", " . $top_referrer_result->referrer_name . "(" . $top_referrer->row_count . ")"; ?></li>
<li>
<form method="POST" action="http://keepmecertified.com/acp">
<input type="submit" value="click me" name="export_tbl_one"/>
</form>
</li>
</ul>
</div>
<br>
<table class="table">
<caption>Referrer Transactions</caption>
<?
$num = 0;
foreach($ref_transactions_table_arr as $fields)
{
echo "<tr>";
foreach($fields as $data)
{
if($num == 0)
{
echo "<th class=\"ref_head\">$data</th>";
}
else
{
echo "<td>$data</td>";
}
}
echo "</tr>";
if($num == 0)
{
$num++;
}
}
?>
</table>
<table class="table">
<caption>Active Referrers</caption>
<?
$num = 0;
foreach($active_ref_table_arr as $fields)
{
echo "<tr>";
foreach($fields as $data)
{
if($num == 0)
{
echo "<th class=\"ref_head\">$data</th>";
}
else
{
echo "<td>$data</td>";
}
}
echo "</tr>";
if($num == 0)
{
$num++;
}
}
?>
</table>
Try this code:
$csvData = array(
array("1","2","3","4"),
array("2","1","6","6")
);
$fp = fopen('php://memory', 'w+');
foreach ($csvData as $row) {
fputcsv($fp, $row);
}
rewind($fp);
$csvFile = stream_get_contents($fp);
fclose($fp);
header('Content-Type: text/csv');
header('Content-Length: '.strlen($csvFile));
header('Content-Disposition: attachment; filename="file.csv"');
exit($csvFile);
I have looped the data to build the CSV as your code would not produce the result you expect. I have also retrieved the file as a string before outputting - this is just a nicety to add a Content-Length header. I have also - and this is the important bit - called exit to output the data, to prevent any more code being executed any prevent and HTML after this code being output.
If you are using this code and still having a problem, then the code is not being called - you should check any if statements etc that this code is wrapped in.
This is way late but let's hope this unblocks someone.
Use ob_end_clean() to clean out other buffers on the page.
Start with ob_end_clean(); and end with exit;
This way, only the output in between will be written to the file.