PHPWORD generates "mirrored" table instead of normal - phpdoc

I use PHPWORD library to generate .docx document with a simple table.
This is the code:
require "vendor/autoload.php";
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$phpWord->setDefaultFontName('Arial');
$phpWord->setDefaultFontSize(12);
$properties = $phpWord->getDocInfo();
$properties->setCreator('My doc');
$properties->setCompany('My doc');
$properties->setTitle('My doc');
$properties->setDescription('My doc');
$properties->setCategory('My doc');
$properties->setLastModifiedBy('My doc');
$properties->setCreated(time());
$properties->setModified(time());
$properties->setSubject('My doc');
$properties->setKeywords('My, Doc, Yeah');
$sectionStyle = array(
'orientation' => 'portrait',
'marginTop' => \PhpOffice\PhpWord\Shared\Converter::pixelToTwip(40),
'marginLeft' => \PhpOffice\PhpWord\Shared\Converter::pixelToTwip(40),
'marginRight' => \PhpOffice\PhpWord\Shared\Converter::pixelToTwip(40),
'colsNum' => 1,
'pageNumberingStart' => 1,
'borderBottomSize'=>100,
'borderBottomColor'=>'ffffff'
);
$section = $phpWord->addSection($sectionStyle);
$html2 = '<table>';
$html2 .= '<tr>';
$html2 .= '<td>Something 1</td>';
$html2 .= '<td>Something 2</td>';
$html2 .= '</tr>';
$html2 .= '<tr>';
$html2 .= '<td>Another 1</td>';
$html2 .= '<td>Another 2</td>';
$html2 .= '</tr>';
$html2 .= '</table>';
\PhpOffice\PhpWord\Shared\Html::addHtml($section, $html2);
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="first.docx"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$xmlWriter->save("php://output");
So the document is generated, but the table in it is shown not like this:
Something 1 | Something 2
Another 1 | Another 2
But like this:
Something 2 | Something 1
Another 2 | Another 1
So for some reason it is "mirrored" in generated .docx. Here is an attached imaged of the .docx - https://ibb.co/1McSS0y. What is the reason?

Related

Export Data As CSV In CodeIgniter

I need to export results from a MySQL query into a csv file in codeigniter.
This is the model:
public function export_csv()
{
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$delimiter = ",";
$newline = "\r\n";
$file_name = 'BVN_REPORTS'.date("Y-m-d h-i-s").'.csv';
$query = 'SELECT account_name as "Account Name",
api_account_name as "Verified Name",
account_num "Account Number",
bvn "Bank Verification Number (BVN)", bank_name as "BANK NAME"
from ew_employees where bvn is not null
ORDER BY bank_name ';
$result = $this->db->query($query);
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
if(force_download($filename, $data)){
echo 'Done';
}
else {echo 'Not Done';}
}
And this is the controller:
public function get_csv()
{
$this->load->model('employees_model');
$this->employees_model->export_csv();
}
The result is always 'Not Done'...how can i force a csv download of the query results.Thanks
According to the Question title let me Answer the question.Generally it may help other when visit here.
what i generally do when exporting data to csv.
function data_to_csv($data, $headers = TRUE, $filename= "")
{
if ( ! is_array($data))
{
show_error('invalid Data provided');
}
$array = array();
if ($headers)
{
$array[] = array_keys($data[0]);
}
foreach ($data as $row)
{
$line = array();
foreach ($row as $item)
{
$line[] = $item;
}
$array[] = $line;
}
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=\"$filename".".csv\"");
header("Pragma: no-cache");
header("Expires: 0");
$handle = fopen('php://output', 'w');
foreach ($array as $array) {
fputcsv($handle, $array);
}
fclose($handle);
exit;
}
controller
$result = $this->registration_model->exportToCsv();
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=\"application".".csv\"");
header("Pragma: no-cache");
header("Expires: 0");
$handle = fopen('php://output', 'w');
fputcsv($handle, array('Sr No.', 'Apply for', 'Name', 'mobile', 'email_id', 'work_experinece', 'pan', 'refrence', 'pro_img1', 'pro_img2', 'created_at'));
$i = 1;
foreach ($result as $data) {
fputcsv($handle, array($i, $data["apply_for"], $data["full_name"], $data["mobile"], $data["email_id"], $data["work_experinece"], $data["pan"], $data["refrence"], $data["pro_img1"], $data["pro_img2"], $data["created_at"]));
$i++;
}
fclose($handle);
exit;
Model
$this->db->select("apply_for,full_name,mobile,address,email_id,work_experinece,pan,refrence,pro_img1,pro_img2,created_at");
$this->db->order_by("app_id", "DESC");
$this->db->from("tablename");
$query = $this->db->get();
return $query->result_array();
I added a line to Abdul Manan's answer to deal with UTF-8 characters :
foreach ($array as $array) {
fputs($handle, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
fputcsv($handle, $array);
}

Joomla archive by year?

I posted this question before, but it got drowned and barely got any views so I figured I'd try one more time.
This seems like such a strange thing to not exist yet but I've been looking for ages. Is there an archive plug-in or component, or any way really, to simply sort the archive by year? All I want is to display columns for each year, with the year displayed above each column, containing a (clickable) list of archived titles. I'm using Joomla 2.5.
Anyone know how to do this? Whether it's through a plug-in/component or editing the existing archive code; don't care how, just want to get it done. Any help would be much appreciated.
You could try these extensions:
JExtBOX Article History - 5$
Demo : http://demo.jextbox.com/
Monthly Archive
Demo: http://www.joomla357.com/demo/monthly-archive.html - ?$
Mod LCA
Demo: http://www.jonijnm.es/web/mod-lca.html - free
This might not be an ideal solution and not too clean either, but I used Monthly Archive and changed the getMonths() method in the monthlyarchiveclass to include this:
$byYear = array();
foreach($month_years_unique as $month_year){
$year = explode('-',$month_year);
$byYear[$year[1]] = array();
}
foreach($results_months as $result){
$year = $result['year'];
$id = $result['id'];
$byYear[$year] = array(
$id => $result,
);
}
if(count($byYear) != 0){
foreach($byYear as $year => $value){
$html .= '<div class="archivecolumn"><h1>'.$year.'</h1>';
$html .= '<ul class="itemlist">';
foreach($value as $item){
$cat = $this->getCatName($item['catid']);
$link = 'index.php/' . $cat . '/' . $item['id'] . '-' . $item['alias'];
$html .= '<li>';
$html .= ''.$item['title'].'';
$html .= '</li>';
}
$html .= '</ul>';
$html .= '</div>';
}
} else {
$html .= 'No archived works.';
}

Cannot get SwiftMailer to Successfully Send HTML Embededd Images

When I add images to my email, SwiftMailer notifies that it has been sent, but I do not see it in my inbox, and there are not PHP errors neither.
On the other hand, without the images, the HTML, is successfully sent to my inbox. When I strip tags from the HTML message and send, I get the images alone in my inbox.
I have been dealing with this for about 3 days, and researching for a workable solution to no avail. Any help will be appreciated.
Thanks.
require_once 'Swift_Mailer/swift_required.php';
$message = Swift_Message::newInstance();
$img1 = $mail->embed( Swift_Image::fromPath( IMGFILEPATH . "img1.png" ));
$img2 = $mail->embed( Swift_Image::fromPath( IMGFILEPATH . "img2.png" ));
$subject = "To Whom It May Concern.";
$msg = "<body><div style='background:#002211; padding:10px;'><a href='" . $url . "' target='_BLANK'><img src='" . $img1 . "' id='image1' class='BORDERZERO' alt='GC' /> <img src='" . $img2 . "' id='image2' class='BORDERZERO' alt='General Collections Box.' /></a></div>";
$msg .= "<hr style='color:#555555; height:1px; background:#777777; vertical- align:top;'/><div style='padding:10px; background:#777777; color:#000000;'>";
$msg .= "<span>Hello,<br /><br />We would like to say thank you for donating to our collections box.<br /><br />The General Collections Box.<br />
$msg .= "<hr style='color:#555555; height:2px;' />";
$msg .= "If you believe that this message was sent to you in error or that you are not the intended recipient, please simply discard and disregard it. Thank you for your cooperation. - GBC.<br /></span></div></body>";
$message->setSubject( $subject )->setFrom( array( $sender => $sender_name ))
->setTo( array( $recipients ))->setBody( $html, "text/html" )
->addPart( strip_tags( $html ), "text/plain" )->setPriority( 2 )
->setReadReceiptTo( "$sender" );
if( !MMCS_Service::getSwiftMailer()->send( $mail, $failures )){
var_dump( $failures );
exit( 0 );
}

fsockopen demo at localhost

Can anybody help me to sort out fsockopen issue in localhost.
I created fsock.php to post a variable to test121.php in the same folder.
http://localhost/ftp/fsock.php
<?php
$fp = fsockopen('localhost/ftp');
$vars = array(
'hello' => 'world'
);
$content = http_build_query($vars);
fwrite($fp, "POST /test121.php HTTP/1.1\r\n");
fwrite($fp, "Host: localhost/ftp \r\n");
fwrite($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
fwrite($fp, "Content-Length: ".strlen($content)."\r\n");
fwrite($fp, "Connection: close\r\n");
fwrite($fp, "\r\n");
fwrite($fp, $content);
header('Content-type: text/plain');
while (!feof($fp)) {
echo fgets($fp, 1024);
}?>
This was the code in test121.php
http://localhost/ftp/test121.php
<?php
echo "<br><br>";
$raw_data = $GLOBALS['HTTP_RAW_POST_DATA'];
parse_str( $raw_data, $_POST );
//test 1
var_dump($raw_data);
echo "<br><br>";
//test 2
print_r( $_POST );
?>
I am getting Failed to parse address error in fsock.php.
Can anybody explain me how to sortout this issue in localhost.
Thank you in advance.
fsock.php
$fp = fsockopen("localhost", 80, $errno, $errstr, 30);
$vars = array(
'hello' => 'world'
);
$content = http_build_query($vars);
fwrite($fp, "POST http://localhost/ftp/test121.php HTTP/1.1\r\n");
fwrite($fp, "Host: localhost \r\n");
fwrite($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
fwrite($fp, "Content-Length: ".strlen($content)."\r\n");
fwrite($fp, "Connection: close\r\n");
fwrite($fp, "\r\n");
fwrite($fp, $content);
header('Content-type: text/plain');
while (!feof($fp)) {
echo fgets($fp, 1024);
}?>
And you might also want to change test121.php and remove $GLOBALS (Not sure why you using this):
<?php
echo "<br><br>";
$raw_data = $_POST;
//test 1
var_dump($raw_data);
echo "<br><br>";
//test 2
print_r( $_POST );
?>

PDF attachment shows up in Gmail but Outlook refuses to open it

I'm relatively new to php.
I wrote a script that sends an email with a pdf attachment to a user and a confirmation to a co-worker. Everything works fine in web-based email clients like gmail but the pdf attachment does not open when it is received in Outlook. It also adds another attachment called "ATT0159.txt" which is completely blank.
Here's the code:
<?php
$pdf = $_GET['pdf'];
$product = $_GET['product'];
$username = $_POST['Name']; #get name
$useraddress = $_POST['Email']; #get user email address
$subjectUser = $product . " PDF brochure from Specifile on-line";
$to = "specifile#gmail.com"; # recipient
$subject = "Confirmation: PDF Request - " . $product; #subject
$message = "The following person has requested the brochure - " . $product . "\n<br/>" . $username . " [ " . $useraddress . " ] "; #message
$attachment = $_SERVER['DOCUMENT_ROOT'] . "\\" . $pdf;
$attachment_type = "application/pdf";
$attachment_name = "brochure.pdf";
#open, read, then close the file
$fp = fopen( $attachment, 'rb');
$file = fread($fp, filesize($attachment));
fclose($fp);
#create boundary string
$num = md5(time());
$str = "==Multipart_Boundary_x{$num}x";
#encode data for safe transit
$file = chunk_split(base64_encode($file));
#define user header
$headers = "MIME-version: 1.0\r\n";
$headers .= "Content-type: multipart/mixed;\r\n";
$headers .= " boundary=\"{$str}\"\r\n";
$headers .= "From: Specifile on-line<specifile#infixion.co.za> \r\n";
#define confirmation header
$Confirmheaders = "MIME-version: 1.0\r\n";
$Confirmheaders .= "Content-type: text/html;";
$Confirmheaders .= " charset=\"UTF-8\"\r\n";
$Confirmheaders .= "From: Specifile on-line<specifile#infixion.co.za> \r\n";
#create message for user
$messageUser = "This is a multi-part message in MIME format\r\n";
$messageUser .= "--{$str}\r\n";
$messageUser .= "Content-type: text/html; charset=\"UTF-8\"\r\n";
$messageUser .= "Content-Transfer-Encoding: 8bit\r\n";
$messageUser .= "Hi " . $username . ", <p>The brochure you requested is attatched.</p> \r\n\n";
$messageUser .= "--{$str}\r\n";
#define non text attachment
$messageUser .= "Content-Type: {$attachment_type}; ";
$messageUser .= "name=\"{$attachment_name}\"\r\n";
$messageUser .= "Content-Disposition: attachment; ";
$messageUser .= "filename=\"{$attachment_name}\"\r\n";
$messageUser .= "Content-Transfer-Encoding: base64\r\n";
$messageUser .= "$file\r\n\n";
$messageUser .= "--{$str}";
mail($useraddress,$subjectUser,$messageUser,$headers);
mail($to,$subject,$message,$Confirmheaders);
?>
Not a real answer to your question, but have you considered using a ready-made mailing class like SwiftMailer? It does building the multipart message, and adding the attachments, for you.

Resources