Follow me on Twitter to receive updates, free scripts and ongoing announcements!

PHP xml to csv

Written by Codes Tips on May 23, 2009 – 7:48 am -

To create a csv file from a xml in PHP 5.0 it’s very simple, we will just have to write some lines.
We will use the SimpleXML extension that come from PHP 5.0.
SimpleXML reads an entire xml into an object that we can iterate through his properties.
To write to the csv output file we will use fputcsv.
fputcsv formats a line as csv and writes it to the file.
Suppose we are having this xml named cars.xml:

<?xml version='1.0'?>
<cars>
<car>
 <color>blue</color>
 <price>2000</price>
</car>
<car>
 <color>red</color>
 <price>10000</price>
</car> 
<car>
 <color>black</color>
 <price>5000</price>
</car>
</cars>

First we should read our xml using simplexml_load_file passing the name of the file and returns an object with all the properties and values of the csv:

    $xml = simplexml_load_file($filexml);

After reading it we should iterate through all the child nodes of cars and write it to the output file using fputcsv specifying the object,delimiter and enclosure. We should first convert the object into an array in order to write it to the csv:

foreach ($xml->car as $car) 
fputcsv($f, get_object_vars($car),',','"');

Here is the complete source code that converts xml to csv in php 5.0:

<?
$filexml='cars.xml';
if (file_exists($filexml)) {
    $xml = simplexml_load_file($filexml);
$f = fopen('cars.csv', 'w');
foreach ($xml->car as $car) {
    fputcsv($f, get_object_vars($car),',','"');
}
fclose($f);
}
?>

Download php source code for converting xml into a csv


Tags: ,
Posted in Codes, PHP/MYSQL, Scripts | No Comments »

PHP multithreading using cURL

Written by Codes Tips on May 23, 2009 – 3:00 am -

If you wanna get some information from servers using the protocols like http or ftp in PHP you can use cURL to do multithreading.
Multithreading is a term used when we do more jobs in parallel.
First I assume you know what cURL is and what you can it. If you are new to cURL, you can check one of my article on posting data with cURL , it will give you a brief intro to cURL.
To create this with cURL you should know what the following PHP functions do:
curl_multi_init - initialize a new cURL multi handle. It will return the cURL handle on success and FALSE on error.
curl_multi_add_handle — Add a cURL handle to a cURL multi handle.
curl_multi_exec — Runs all the curl handle in the cURL multi handle in parallel.
curl_multi_remove_handle — Removes a cURL handle from a cURL multi handle.
curl_multi_close — close the cURL multi handle.
You will need at least PHP 5.0 installed on your server in order this cURL function to work.

So now that you know what this functions do, we should first create the links to the servers from were we wanna get info. I will assume that we wanna get information from 3 servers simultaneous:

$list[1] = "http://www.example1.com";
$list[2] = "ftp://example.com";
$list[3] = "http://www.example2.com";

After creating the list of links we should initialize the cURL multi handle and adding the cURL handles.

$curlHandle = curl_multi_init();
for ($i = 1;$i <= 3; $i++)
 $curl[$i] = addHandle($curlHandle,$list[$i]);

Now we should execute the cURL multi handle retrive the content from the sub handles that we added to the cURL multi handle.

ExecHandle($curlHandle);
for ($i = 1;$i <= 3; $i++)
{
 $text[$i] =  curl_multi_getcontent ($curl[$i]);
 echo $text[$i];
}

In the end we should release the handles from the cURL multi handle by calling curl_multi_remove_handle and close the cURL multi handle:

 
for ($i = 1;$i <= 3; $i++)//remove the sub - handles
  curl_multi_remove_handle($curlHandle,$curl[$i]);
curl_multi_close($curlHandle);

Here is the complete code for doing multithreading in php with cURL:

<?
//add a url to the handler
function addHandle(&$curlHandle,$url)
{
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HEADER, 0);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle($curlHandle,$cURL);
return $cURL;
}
//execute the handle until the flag passed
// to function is greater then 0
function ExecHandle(&$curlHandle)
{
$flag=null;
do {
//fetch pages in parallel
    curl_multi_exec($curlHandle,$flag);
} while ($flag > 0);
}
 
 
$list[1] = "http://www.example1.com";
$list[2] = "ftp://example.com";
$list[3] = "http://www.example2.com";
$curlHandle = curl_multi_init();
for ($i = 1;$i <= 3; $i++)
 $curl[$i] = addHandle($curlHandle,$list[$i]);
ExecHandle($curlHandle);
for ($i = 1;$i <= 3; $i++)
{
 $text[$i] =  curl_multi_getcontent ($curl[$i]);
 echo $text[$i];
}
for ($i = 1;$i <= 3; $i++)//remove the handles
  curl_multi_remove_handle($curlHandle,$curl[$i]);
curl_multi_close($curlHandle);
?>

Download complete source


Tags:
Posted in Codes, PHP/MYSQL | 1 Comment »

PHP ajax cascading dropdown using MySql

Written by Codes Tips on May 16, 2009 – 5:31 pm -

To do cascading drop down in php using mysql we can use AJAX. The name AJAX is from asynchronous JavaScript and XML and it’s a new technique for web development to build rich interactive web application. The power of this technique comes from the fact that it can send to server requests from the client side, in order to not reload the page. The object that is using AJAX to send and retrieve data between server and the client is named XmlHttpRequest.
To build a cascading drop down in php to retrieve data from a mysql server we will first populate a drop down with the results from a first table from a mysql database. The first table is linked with a second table by a field. When we change the drop down we should assign to OnChanging event an Javascript function that will populate the second drop down . The function will create a new XmlHttpRequest object and make a call to other php script, grab data and populate the second drop down. The script that it’s called will fetch the results for that field that was changed.

Watch a demo here:populate drop down using ajax

Download php cascading drop down using mysql


Tags: , ,
Posted in AJAX, Codes, PHP/MYSQL, Scripts | 15 Comments »

Delphi usefull string functions

Written by Codes Tips on May 10, 2009 – 2:24 pm -

This is a list of functions to handle strings in Delphi. It will be update periodically.

Function Stream to String.
If you wanna convert a stream to a string you need to create a TMemoryStream variable and use the function SetString to put the result string

function StreamToString(Stream : TStream) : String;
var ms : TMemoryStream;
begin
  Result := '';
  ms := TMemoryStream.Create;
  try
    ms.LoadFromStream(Stream);
    SetString(Result,PChar(ms.memory),ms.Size);
  finally
    ms.free;
  end;
end;

Function Replace Char
To replace a char with other character you should make a loop until that char is not find in the string. If it is found in the string then replace with the new character. To find position of a character in a string you should use the function pos and return the position in the string where it was found. If it was not found pos returns -1

function ReplaceChar(s:string;c:char;charrep:char):string;
 begin
   while pos(c,s)>0 do
       s[pos(c,s)]:=charrep;
    ReplaceChar:=s;   
 end;

Function Remove Tags

Function RemoveTags(s:string):string;
var k1:integer;
     s1:string;
     canwrite:boolean;
begin
 
 s1:='';
 canwrite:=true;
for k1:=1 to length(s) do
 begin
   if s[k1]='<' then
     canwrite:=false
   else
     if s[k1]='>' then
        canwrite:=true
      else
       begin
        if canwrite then
         s1:=s1+s[k1];
       end;
 
 end;
  RemoveTags:=s1;
end;

Tags: ,
Posted in Delphi | No Comments »

Delphi enable and disable proxy in IE

Written by Codes Tips on May 10, 2009 – 2:09 pm -

To change the proxy that you connect to internet by code in delphi you need to change the values of 2 fields from the folder settings of Internet Explorer in the registry. Basically you should change the registry values of 2 fields ProxyServer and ProxyEnable. First to use a proxy server you should enable the field ProxyEnable, by setting it to 1. Proxy server is the formatted like server:port and tell the browser through which server should connect.
You should include in the uses cause Registry.
Here is a sample function to change proxy server for internet explorer:

procedure EnableProxy( proxy:string; proxyp:string);
var Reg: TRegistry;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey(’\Software\Microsoft\Windows\CurrentVersion\Internet Settings’, True) then
begin
Reg.WriteString(’ProxyServer’,proxy+’:'+proxyp);
Reg.WriteInteger(’ProxyEnable’,1);
Reg.CloseKey;
end;
finally
Reg.Free;
end;

end;

To disable the proxy by in internet explorer you should set the field ProxyEnable to 0. Here is how to do it:

procedure DisableProxy;
var Reg: TRegistry;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey(’\Software\Microsoft\Windows\CurrentVersion\Internet Settings’, True) then
begin
Reg.WriteInteger(’ProxyEnable’,0);
Reg.CloseKey;
end;
finally
Reg.Free;
end;
end;


Tags: ,
Posted in Delphi | No Comments »

Binary search in string array

Written by Codes Tips on May 10, 2009 – 2:04 pm -

To search an string into an array of string you can iterate through all the strings one by one and test which is the string that we wanna search. Doing this you will have a complexity of O(n), where n is the number of the strings that array have.
To do search more efficient you should use binary search which have a complexity of O(log2(n)). To use the binary search method in an array of string we assume that we have a sorted array. To sort an array of string efficiently you can use for example Quicksort algorithm , that was previously described, to obtain a good complexity. Of course, you should use binary search algorithm when you are doing something complex that have a complexity bigger or equal to O(n^2).
So to search a string in an array the algorithm selects the middle element of the array and verify if it is equal to our string. If it is equal it stops, if not it sees if the string is bigger then our string and if it is, it searches in the right part of the array string, if not in left part, applying the same algorithm. So it uses a recursive function to search the string in the array.

We will use the following type of string and declare a variable:

type  arraystrings=array[1..1000000] of string;
var words:arraystrings;

Here is the binary search algorithm:

 
function BinSearch(word:string;l:integer;h:integer):integer;
 begin
    while (StrIComp(pchar(word),pchar(words[(l+h)div 2]))<>0)and(l<>h) do
      begin
         if strIcomp(pchar(word),pchar(words[(l+h)div 2]))>0 then
            l:=(l+h)div 2+1
          else
            h:=(l+h)div 2-1;
      end;
    if l<>h then
     BinSearch:=(l+h)div 2
    else
     BinSearch:=0;
 end;

It returns the position in the array where it was found. If not returns 0.
To call it you can use:

position:=BinSearch(word,1,nrwords);

where word is the string we search for and nrwords it’s the number of strings in the array.


Tags: ,
Posted in Algorithms, Codes, Delphi | No Comments »

Quicksort array of string

Written by Codes Tips on May 10, 2009 – 1:33 pm -

Quicksort it’s an algorithm that it’s very efficient when you wanna sort an array of any type: string, integer, real. I will show you how to sort an array of string, it can be modified easily to sort other types of array.
Quicksort it’s efficient because it’s having a sorting complexity of O(n* log2(n)). An usual sorting algorithm like bubble sort or merge sort it’s taking O(n^2), which it’s very inefficient for array with over 5000 elements.
I will write an implementation of this algorithm in Delphi.
The Quicksort algorithm it’s very similar to divide and conquer algorithm because it splits the array into to sub arrays, sort those sub arrays and put them together after into 1 array sorted. For sorting those array it uses a pivot that it’s positioned in the middle of the array and put in the left, strings that are lower and in the right, the strings that are higher. So for doing this it uses a recursive function because for every sub array divides again in 2 sub array and sort them. So after sorting each sub array , we will have in the final step all the array sorted.

Here is an implementation of Quicksort array of string in Delphi.
First declare a type of array string:

type arraystrings=array[1..100000] of string;

Quicksort algorithm:

procedure QuickSort(var A: arraystrings; Lo, Hi: Integer);
 
procedure Sort(l, r: Integer);
var
  i, j,aux: integer;
  y,x:string;
begin
  i := l; j := r; x := a[(l+r) DIV 2];
  repeat
    while strIcomp(pchar(a[i]),pchar(x))<0 do i := i + 1;
    while StrIComp(pchar(x),pchar(a[j]))<0 do j := j - 1;
    if i <= j then
    begin
 
      y := a[i]; a[i] := a[j]; a[j] := y;
      i := i + 1; j := j - 1;
    end;
  until i > j;
  if l < j then Sort(l, j);
  if i < r then Sort(i, r);
end;
 
begin 
  Sort(Lo,Hi);
 
end;

Tags: ,
Posted in Algorithms, Codes, Delphi | 2 Comments »

Blog design changed

Written by Codes Tips on May 9, 2009 – 4:03 pm -

Friends told me that I Because of some displaying problems in Internet Explorer of the site I decided to change design of my blog. Hope you like it!


Posted in Announcements | No Comments »

PHP copy directory from source to destination

Written by Codes Tips on May 2, 2009 – 1:02 pm -

To copy a directory source to a destination directory you will need to scan the source directory with all files and directory and copy to the destination. To accomplish this we should make a recursive function that will copy the files from source to target dir. If it is not a directory in the source dir we should just copy the file to target. If it is a directory in the source dir then we should create a new dir in the target directory and apply the same mechanism, so we need to recall again the same function.
Here is the code to do this:

<?
function copy_directory( $source, $destination ) {
	if ( is_dir( $source ) ) {
		@mkdir( $destination );
		$directory = dir( $source );
		while ( FALSE !== ( $readdirectory = $directory->read() ) ) {
			if ( $readdirectory == '.' || $readdirectory == '..' ) {
				continue;
			}
			$PathDir = $source . '/' . $readdirectory; 
			if ( is_dir( $PathDir ) ) {
				copy_directory( $PathDir, $destination . '/' . $readdirectory );
				continue;
			}
			copy( $PathDir, $destination . '/' . $readdirectory );
		}
 
		$directory->close();
	}else {
		copy( $source, $destination );
	}
}
?>

Calling the function:

copy_directory('dirnameSource','dirnameDestination');

Download copy directory code


Tags: ,
Posted in Codes, PHP/MYSQL | 1 Comment »