PHP pdf generator from html

I will explain in this article how to make a pdf generator from html in php.
We will use a command tool that will generate the pdf. It’s an open source shell utility that is called wkhtmltopdf that uses webkit rendering engine, and qt – go here for more information for wkhtmltopdf. I suggest to use the version 0.9.9, which I think it’s a stable version right now. I tested the version 0.11.0_rc1 and I got some problems with downloading the images from html img tag.
Steps to generate the pdf from html:
1. Download the tool.
2. Install the tool.
3. Use the tool from your php code to create a pdf from html.

1. Depending on your operating system you should download from the following page:

2. To install on Windows should download the .exe from the website, launch the setup and follow the steps. In order to test if you installed correctly the tool you should go to the folder of where you installed it and launch in command prompt the following command: wkhtmltopdf http://www.test.com test.pdf

To install on Linux you should find out the operating system launching the command uname -a that will tell you the operating system you are using and download the apropiate version of the tool.
To install on 32 bits Linux operating system you should use the following code:

//get the file from server
wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9-static-i386.tar.bz2
tar xvjf wkhtmltopdf-0.9.9-static-i386.tar.bz2
// move the application to bin folder
mv wkhtmltopdf-i386 /usr/local/bin/wkhtmltopdf
//change permission for install it
chmod +x /usr/local/bin/wkhtmltopdf
// install it
/usr/local/bin/wkhtmltopdf
//To test if you installed correctly the tool
wkhtmltopdf-i386 http://www.test.com test.pdf

To install on 64 bits Linux operating system you should use the following code:

//get the file from server
wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.9.9-static-amd64.tar.bz2
tar xvjf wkhtmltopdf-0.9.9-static-amd64.tar.bz2
// move the application to bin folder
mv wkhtmltopdf-amd64/usr/local/bin/wkhtmltopdf
//change permission for install it
chmod +x /usr/local/bin/wkhtmltopdf
// install it
/usr/local/bin/wkhtmltopdf
//To test if you installed correctly the tool
wkhtmltopdf-amd64 http://www.test.com test.pdf

3. In php you should execute the tool using shell_exec:

shell_exec("/usr/local/bin/wkhtmltopdf-i386 http://test.com test.pdf");
//for Linux 32 bits operating system
//for Linux 64 bits operating system use wkhtmltopdf-amd64
//for windows just put the path of the exe file.
$allfile = file_get_contents("test.pdf");
header('Content-Type: application/pdf');
header('Content-Length: '.strlen($allfile));
header('Content-Disposition: inline; filename="test.pdf"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');

PHP database logging

In order to make database logging in php we should first create a table with 2 fields: the message that we log and the date that the log was made. After creating the database we should create a php class that will have to pass the instance of the MySQL database to the log class contructor. After that as previous example of php log file we should call a function that inserts a new row in a table database. Here is the class for php database logging:


class DBLog {
private $_db;

public function __construct($db) {
$this->_db = $db;
}

public function WriteLogToDB($message) {
if(!empty($message)){
$date = date("Y-m-d h:m:s");
mysql_query ("INSERT INTO DBLog VALUES('".$message."', '$date')", $this->_db);
}
}
}

In order to call the function of database logging we should first make a connection to the database and then call the function to save row log to database:


$connection = mysql_connect("localhost", "username", "password")
or die("Unable to connect to MySQL server");
mysql_select_db('DatabaseName', $connection) or die ("Database not found.");
$filel = new DBLog($connection);
$filel->WriteLogToDB('Here is my first log.');

We only need the mysql script that creates the table in our database:


CREATE TABLE IF NOT EXISTS `dblog` (
`Message` text NOT NULL,
`DateCreated` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Tags: ,

PHP file log

Writing a file log on disk with php it’s pretty straigt forward. Here is a simple php class that can help you log to a file. The class is logging on the directory where the script exists. You can also create a directory where the script inside and change the path in order to log to the directory you created. In the constructor of the class you should pass the name of the log file. Every time you call the function WriteLogToFile it appends messages in the file log of the directory script.


class FileLogger{
private $filename;
public function __construct($file) {
$this->filename = $file;
}

public function WriteLogToFile($messageLog) {
$currentDir = dirname(__FILE__)."/";
$fileLog = fopen($currentDir.$this->filename, 'a+');
fwrite($fileLog, $messageLog."\r\n");
fclose($fileLog);
}
}
?>

Calling function example:
$filel = new FileLogger('file.log');
$filel->WriteLogToFile('log...');

Tags: , , ,

JQuery posts

Hi,

It was some time that I didn’t wrote on codestips. I want to start some posts about JQuery and Facebook development.

If you thought how to build rss feed parser you should think first think about what php xml parse you should use. If we examine the parser that we have built in then you will find expat, simple xml and xml dom manupulation. In order to parse a feed from a url you should first validate the feed url , get the contents of the xml through file_get_contents, and loop through nodes of xml and get the nodes values.
So here are steps the in order to build our class:
1. Validate url
2. Get contents using file_get_contents

3.Set the limit of how many items to return
4. Parse results. We should replace the spaces of the node values.

Class Description
Variables
$url – the url of the feed that will be parsed.
$doc – the DOM Document that will load the xml parsed from url.
$limit – Limits the number of items to be retrieved.
$isValidUrl – Verifies if the link is valid.
$items – the RSS items that would be returned.

Constructor
Initialize the url of the feed and all class variables with empty variables. We initialize the limit to 5 items.
Methods
SetLimit – sets the limit of the items to be parsed
ValidateUrl – validates the url of the rss feed. It checks if the feed url begins with ‘http://’
ExecuteRssParser – fetches the feed url and loads into a php variable. After that it loads the xml and parses the rss nodes values and returns the results into the variable ‘feeds’.

<?
class RssFeedParser
{
private $url, $doc, $limit;
public $isValidUrl, $items;
 
public function __construct($url) {
$this->url = $url;
$this->items = array();
$this->doc = new DOMDocument();
$this->limit = 5;
}
 
private function ValidateUrl()
{
if (stristr( $this->url, 'http://') === FALSE)
{
return false;
}
else
{
return true;
}
}
 
public function SetLimit($limit)
{
$this->limit = $limit;
}
 
public function ExecuteRssParser()
{
$this->isValidUrl = $this->ValidateUrl();
if ($this->isValidUrl)
{
  $xmlText = preg_replace("/>\s+</", "><", file_get_contents($this->url));
  $this->doc->loadXML($xmlText);
 
  if ($this->doc->getElementsByTagName('item'))
  {
	  $count = 0;
	  foreach ($this->doc->getElementsByTagName('item') as $node) {
		$itemRSS = array ( 
		  'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
		  'description' => $node->getElementsByTagName('description')->item(0)->nodeValue,
		  'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
		  'pubDate' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
		  );
		array_push($this->items, $itemRSS);
		$count++;
		if ($count>=$this->limit)
		{
			break;
		}
	  }
  }
}
}
}
?>

You can easy modificate this class in order to fit your needs. Good luck!!!

In order to parse the youtube video id you can use the parse_url and parse_str php functions. You should first parse the url and all it’s components using the php function parse_url. The components we are interested in for parsing the youtube video id you should use the ‘query’ components where are stored all the query strings parameters. We then have to use the parse_str function in order to parse the query string in variables.

The input parameter of the function is the youtube url.
The ouput paramter is the youtube video id.
The php function that returns the youtube video id is:

function GetYouTubeVideoId($youtubeUrl)
{
$link = parse_url($youtubeUrl);
parse_str($link['query'], $qs);
$youtubeId = $qs['v'];
return $youtubeId;
}

PHP downloadable file

Text downloadable file

Last days I needed to create a file which had to be downloaded by many users. The file had to be in plain text and contents from file come from database. Because I didn’t had a separate folder for each user I couldn’t write the information to a file to the server and put a link in order the user to download it. I thought a little bit how to handle it and found a very simple solution to to make a file downloadable to users. I even try to other popular formats like .doc, .xls,.csv,.dat and it works really nice. Extension that I tested it and didn’t worked are .xlsx and .pdf.

In order to make a file downloadable you should modify the header of the page to make Content-type: application/octet-stream and Content-Disposition: attachment; filename=\”downloadableFile.extension\” in order to inform the browser that there is an attachment binary file. The file will open in a window to inform the user it to open it with a default application or save it to disk.
Code for downloadable file:

<?
		header("Content-type: application/octet-stream");
		header("Content-Disposition: attachment; filename=\"downloadablefile.txt\"");
		echo 'Contents of plain text downloadable file';  
?>

CSV downloadable file

The real magic comes when you wanna make csv file downloadable. You can read data from a mysql table and write the contents to a csv file. You should only read contents from a table and using echo output to the file.

<?
		header("Content-type: application/octet-stream");
		header("Content-Disposition: attachment; filename=\"downloadablefile.csv\"");
		$connect = mysql_connect($server, $user, $password)
			or die ("Database CONNECT Error"); 
 		$resultcsv = mysql_db_query($database, "select * from $csvTable");
		while ($query = mysql_fetch_array($resultcsv)) 
		{ 
			echo $query["Name"].",".$query["City"]."\n";
		}
		mysql_close($connect);
?>

Excel downloadable file

Code for generating a excel downloadble file:

<?
		header("Content-type: application/octet-stream");
		header("Content-Disposition: attachment; filename=\"downloadableFile.xls\"");
		$connect = mysql_connect($server, $user, $password)
			or die ("Database CONNECT Error"); 
 		$resultxls = mysql_db_query($database, "select * from $xlsTable");
		while ($query = mysql_fetch_array($resultxls)) 
		{ 
			echo $query["Name"]."\t".$query["City"]."\n";
		}
		mysql_close($connect);
?>

You can look through records from database and output as I did for csv

Doc downloadable file

You can even make a downloadable .doc files by changing the file extension to doc.

<?
		header("Content-type: application/octet-stream");
		header("Content-Disposition: attachment; filename=\"downloadablefile.doc\"");
		echo 'Contents of Word Document.';  
?>
Tags: ,

PHP string manipulation 3

This is the third part about how to manipulate strings in PHP.

Replace all occurrences of sub strings with a replacement string

If you wanna replace all occurrence of a substring inside a string you should use the function str_replace passing as first argument the string(or array of strings) you wanna search, second argument the string(or array of strings) you wanna make the replace, the third is the string you wanna search in and the fourth argument is the number of replacements the function should make. It returns a string after all replacements have been made.
Declaration: mixed str_replace ( mixed $SearchFor, mixed $ReplaceWith , mixed $String[, int &$number] )
Example:

<?php
$string= "This is a str_replace Function Test";
$searchFor = array("Function","Test");
$replaceWith = array("function","test");
echo str_replace($searchFor,$replaceWith,$string);
?>

Output: This is a str_replace function test

Split string one by one

To tokenize string in php you can you the function strtok in order to split a string. Each smaller string it’s separated by a delimeter. It takes as a first argument the string that will be split and the second the delimeter that it is used to split it.
You should call the first time the function as strtok($String,$delimiter) and returns the first string that is delimited. Any subsequent calls of the function should be like strto($delimiter(s)), because the function keeps into memory the variable $String that it’s delimited.
You can specify multiple delimiter
Declaration: string strtok(string $String, string $delimiter(s))
Example:

<?
$string = "This is an strtok Function Test";
$tok = strtok($string, " ");
 
while ($tok !== false) {
    echo "String=$tok<br />";
    $tok = strtok(" ");//returns the next splitted string in the $string variable
}
?>

Output:
String=This
String=is
String=an
String=strtok
String=Function
String=Test

Split a string by a delimeter

Disadvantage of strtok function it’s that you should call it every time you wanna split the string. You can use explode function in order to split the string and returns an array of string with all the string splitted. The first argument is the delimiter, the second the string you wanna split and you can also specify an optional integer argument that specify the limit of strings splitted.
Declaration: array xplode(string $delimiter , string $String[, int $limit ])
Example:

<?
$string = "This is an explode Function Test";
$explodedstring = explode(" ", $string,3);
 
foreach($explodedstring as $substring)
 echo $substring.'<br />';
?>

Output:
This
is
an explode Function Test

Union elements of array in a string

If you wanna join array elements into 1 string you should call the function implode. The first argument that you should pass to the function is the separation and the second one the array of string.
Declaration: string implode ( string $separator , array $Strings)
Example:

<?
$strings = array('This','is','a', 'implode','function','test');
$separator = " ";
echo implode($separator,$strings);
?>

Output:
This is a implode function test

Replace a string by regular expression

You can use regular expression in php to replace using the function preg_replace. You should pass the first argument as a regular expression pattern – it can be a string or an array of string, the second is the string or array of string that you use to replace the pattern, third argument is the string you search in. The final two arguments are optional, first parameter is the limit of replacement you should make and the final one is the value of replacements that have been made in the string.
Declaration: mixed preg_replace (mixed $regularExpression, mixed $replaceWith, mixed $String [, int $limit= -1 [, int &$count ]] )
Example:

<?
$string = "This is a preg_replace bad, words, Function Test";
$pattern = "(\w+,)";
$replaceWith = "";
echo preg_replace($pattern, $replaceWith, $string)."<br />";
?>

Output:
This is a preg_replace Function Test

PHP string manipulation – part 2

Tags: ,

PHP string manipulation 2

This is the second part of the how you can manipulate string in PHP.

Find length of a string

If you want to find out how many characters have a string you can use the function strlen. If you have to pass 1 argument as the string you wish you find out the length and it returns an integer.
Declaration: int strlen(string text)
Example:

Output: 31

Find a sub string inside a string

To find a first occurrence of a string inside other you should use the function strstr and pass it 2 arguments. First argument should be the string in which you wanna look and the second should be the string you search. It returns part of the first occurrence until the end of the string you search in.
Declaration: string strstr(string searchIn,string lookfor)
Example:

Output: strstr Function Test

Find a string inside other string(case insensitive)

To find an occurrence of a string inside another with case insensitive activated you should use the function stristr. It has the same parameters as the strstr, but it also finds case insensitive strings.
Declaration: string stristr(string SearchIn, string lookFor)
Example:

Output: StrStr Function Test

Find position of first occurrence of a string inside another

To find the position of the first occurrence of a string you can use the function strpos. You should pass two arguments. The first parameter is the string you wanna search in and the second is a the string you are looking for. You can specify an additional argument, an offset that indicates from where position the search should begin.
Declaration: int strpos ( string $SearchIn, mixed $SearchFor[, int $offset= 0 ] )
Example:

Output: 11

Find a position of a string inside another(case insensitive)

You can use the function strripos and it has the same arguments as strpos, but it searches for case insensitives.
Declaration: int strripos ( string $SearchIn, mixed $SearchFor[, int $offset= 0 ] )

How to return parts of a string

To return parts of a string you should use the substr function and pass it 2 arguments and 1 optional. The first argument is the string you wanna return a part of a string, second is the start position from where you wanna begin crop the string. You can also specify an argument with the length that the function should crop.
Declaration: string substr ( string $SearchIn , int $from [,int $length])
Example:

Output: is a substr

Insert after each end of line in string a html br tag

To insert html tag br after the new lines in a string you can use the function nl2br. Function takes one neccessary argument and one optional. First is a string where it will be inserted the br tag and the second one is a boolean that indicates if the replacement is a XHTML compatible line breaks(default value is TRUE).
Declaration: string nl2br(string $InsertIn [,bool $isXHTML= true])
Example:

Output:
This is a nl2br<br /> Function<br /> Test

PHP string manipulation – part 1PHP string manipulation – part 3

Tags: ,

PHP string manipulation

This is a first part of PHP string manipulation.
It’s extremelly useful to know how to manipulate strings in PHP. This tutorial will guide you through how to use the functions that PHP offers.
A string in PHP it’s defined in php in a variable assigning a single or double quote value like:
$string = ‘This is a test string’;
$string = “This is a test string”;

Make all letters from string lowercase

To make every letter of a string in lowercase you should use the function strtolower like this:

<?
$string= "This is a  strtolower Function Test";
echo strtolower($string);
?>

The ouput will be: this is a strtolower function test

Make all letters of a string uppercase

You should use the function strtoupper in order to make every letter of the string in uppercase:

<?
$string= "This is a  strtoupper Function Test";
echo strtoupper($string);
?>

The ouput of will be: THIS IS A STRTOUPPER FUNCTION TEST

Capitalize first letter of each word in a sentence with ucwords

To make a sentence more estetic we can capitalize first letter of each word in a sentence with the function ucwords().

<?
$string= "This is a  ucwords Function Test";
echo ucwords($string);
?> 
Output: This Is A Ucwords Function Test

This function touch only the first letter of each word and leave other characters like they are. We can improve the way how the string is displayed by combining with the strtolower function.

<?
$string= "ThiS is a  ucwords FunctioN Test";
echo ucwords(strtolower($string));
?>

Output will be:This Is A Ucwords Function Test

Remove tabs,spaces,new lines from beginning and end of a string

To remove spaces,tabs and new lines from the beginning and end of a string you should use the function trim(). This function accepts as an input a string, that will be cleaned and returns a string without spaces,tabs and new lines.

<?
$string= "\t \nThis is a  trim Function Test   ";
echo trim($string);
?>

Output: This is a trim Function Test

Remove spaces,tabs and new lines from begining of a string

Similar like trim we can use ltrim to remove spaces,tabs and new lines from the beginning of a string

<?php
$string= "\t \nThis is a  trim Function Test \t\t  ";
echo ltrim($string);
?>

Output: This is a trim Function Test

Remove spaces,tabs and new lines from the end of a string

Similar like ltrim we can use rtrim to remove characters that we don’t need:

<?
$string= "\t \nThis is a  rtrim Function Test \t\t  ";
echo rtrim($string);
?>

Remove tags from a string

To remove tags from a string you should use strip_tags to have a clean string without tags

<?php
$string= "<pre>This is a  trim Function Test</ pre>";
echo strip_tags($string);
?>

PHP string manipulation – part 2

Tags: ,
« Previous posts Back to top