Archive for May, 2009



Push csv entries into an array

A csv with 2 columns, id and email, will be stored respectively in $x
<?php
set_time_limit(300000);

$array2 = file("all.csv");
foreach($array2 as $line)
{
$x[] = list($id[],$email[]) = $line;
}
echo $x[1];
?>

PHP - increment variable name within a loop

<?php
for ( $i = 0; $i <= 10; $i++)
{
${’var’.$i } = $i ;

echo ${’var’.$i};
}
?>

PHP - remove/replace special characters

<?php
// Provides: Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

//Good for ‘trim’ like requirements.
$string = "Here! is some text, and numbers 12345, and symbols !£$%^&";
$new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);

echo $new_string

?>

Curl with wamp

To run curl with wamp/php make sure you uncomment
extension=php_curl.dll
from php.ini in the php and apache/bin folder.

Compare 2 csv’s with PHP

Comparing 2 csv’s with different columns, maintaining structure and integrity.
example:

CSV1
NameA,1
NameB,2
NameC,3
NameD,4
NameE,5
CSV2
5
1
4

$array1 = file("1.csv");
$array2 = file("2.csv");
foreach ($array1 as $line1)
 {
$cat = str_replace($array2, "XOXO", $line1);
echo $cat;
echo "";
}

Result

NameA,XOXO
NameB,2
NameC,3
NameD,XOXO
NameE,XOXO

sort the second column and delete accordingly, useful for filtering out unsubscribers etc etc
can also use
<?php
//prints out existing elements, so result would be ‘a’ and ‘d’
set_time_limit(300000);

$array1 = array(’a',’b',’c',’d');
$array2 = array(’a',’d');

$size= count($array2);
foreach ($array1 [...]

download html page with Curl (Php)

function file_get_contents_curl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$HTML = file_get_contents_curl("http://www.google.ie");