Archive for January, 2011


PHP Functions to Import/Export CSV data

These two function make it very easy to import and export CSV in PHP.
Documentation
CSVEport()

This function has just one argument – the query that returns the necessary data to be exported.

Example: CSVExport(“SELECT name,username,email,url FROM User WHERE status=1″);
CSVImport()

This will upload a CSV file and import the data into the specified table. This function must have the following arguments…

$table
The name of the table the data must be imported to
$fields
An array of fields that will be used
$csv_fieldname
The name of the CSV file field

Example: CSVImport(“User”, array(‘name’,'username’,'email’,'url’), “csv_file”);
Code
//Get the result of the query as a CSV stream.
//http://www.bin-co.com/php/scripts/csv_import_export/
function CSVExport($query) {
$sql_csv = mysql_query($query) or die(“Error: ” . mysql_error()); //Replace this line with what is appropriate for your DB abstraction layer

header(“Content-type:text/octect-stream”);
header(“Content-Disposition:attachment;filename=data.csv”);
while($row = mysql_fetch_row($sql_csv)) {
print ‘”‘ . stripslashes(implode(‘”,”‘,$row)) . “\”\n”;
}
exit;
}

//Import the contents of a CSV file after uploading it
//http://www.bin-co.com/php/scripts/csv_import_export/
//Aruguments : $table – The name of the table the data must be imported to
// $fields – An array of fields that will be used
// $csv_fieldname – The name of the CSV file field
function CSVImport($table, $fields, $csv_fieldname=’csv’) {
if(!$_FILES[$csv_fieldname]['name']) return;

$handle = fopen($_FILES[$csv_fieldname]['tmp_name'],’r');
if(!$handle) die(‘Cannot open uploaded file.’);

$row_count = 0;
$sql_query = “INSERT INTO $table(“. implode(‘,’,$fields) .”) VALUES(“;

$rows = array();

//Read the file as csv
while (($data = fgetcsv($handle, 1000, “,”)) !== FALSE) {
$row_count++;
foreach($data as $key=>$value) {
$data[$key] = “‘” . addslashes($value) . “‘”;
}
$rows[] = implode(“,”,$data);
}
$sql_query .= implode(“),(“, $rows);
$sql_query .= “)”;
fclose($handle);

if(count($rows)) { //If some recores were found,
//Replace these line with what is appropriate for your DB abstraction layer
mysql_query(“TRUNCATE TABLE $table”) or die(“MySQL Error: ” . mysql_error()); //Delete the existing records
mysql_query($sql_query) or die(“MySQL Error: ” . mysql_error()); // and insert the new ones.

print ‘Successfully imported ‘.$row_count.’ record(s)’;
} else {
print ‘Cannot import data – no records found.’;
}
}

Thanks bin-co.com for writing such infomative Articles

Curl Function in GoDaddy Hosting

I use GoDaddy Hosting for this site. A few days ago I tried to use the curl library. Curl was there – but all my calls timed out. I tried different approaches – but all failed. After some google searches I found out why – GoDaddy is using a proxy server.

So if you are using GoDaddy hosting and what to use curl, you should include these lines in the script…

curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
curl_setopt($ch, CURLOPT_PROXY,”http://64.202.165.130:3128″);

…assuming that $ch is the curl handle.

A full example…

<?php
$url = "http://www.google.com/";

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
curl_setopt ($ch, CURLOPT_PROXY,"http://64.202.165.130:3128");
curl_setopt ($ch, CURLOPT_TIMEOUT, 120);
$response = curl_exec ($ch);
if(is_int($response)) {
    die("Errors: " . curl_errno($ch) . " : " . curl_error($ch));
}
curl_close ($ch);

print "Remote Site : $url<br /><hr />$response";
?>

Article is taken from bin-co.com.

Using PHP Short Tags

PHP Short Tags refers to ‘

Short tags are considered bad because they are in conflict with XML’s open tag – ‘

This problem can be solved easily – I use this code…

xml

I use the full tag almost all the time. The only exception is that I use . And I am not prepared to give that up.

I follow the MVC pattern in my projects. My PHP framework, iFrame, is an MVC framework. In the template(view) part, there is a lot of usage of such tags. It is more concise and more readable than the alternative…

You tell me – which is better?

I hear that they will be introducing in PHP 6. Until then, I will continue to use .
This article is from bin-co.com. IT was very usefull for me

Convert PHP arrays to JSON

While we are working with json arrays or calling ajax files that return json in their response sometime we stuck for making json array.
This is because the json array is quite difficult to maintain. You must have to take care of each every special character that is really very difficult if you are thinking to do it manually like “CDATA” for xml.
The best solution that i got from “bin-co.com” is to just make array of PHP and convert it into JSON by using user defined PHP function.

Usage

First you need a PHP array. For example…

$data = array(
‘success’ => “Sweet”,
‘failure’ => false,
‘array’ => array(),
‘numbers’ => array(1,2,3),
‘info’ => array(
‘name’ => ‘Binny’,
‘site’ => ‘http://www.openjs.com/’
)
);

Provide this array as the argument of the array2json() function…

$json = array2json($data);

The resulting string will be(actual output – the source says print array2json($data);)…

{“success”:”Sweet”,”failure”:false,”empty_array”:[],”numbers”:[1,2,3],”info”:{“name”:”Binny”,”site”:”http:\/\/www.openjs.com\/”}}

Code
function array2json($arr) {
if(function_exists(‘json_encode’)) return json_encode($arr); //Lastest versions of PHP already has this functionality.
$parts = array();
$is_list = false;

//Find out if the given array is a numerical array
$keys = array_keys($arr);
$max_length = count($arr)-1;
if(($keys[0] == 0) and ($keys[$max_length] == $max_length)) {//See if the first key is 0 and last key is length – 1
$is_list = true;
for($i=0; $i
if($i != $keys[$i]) { //A key fails at position check.
$is_list = false; //It is an associative array.
break;
}
}
}

foreach($arr as $key=>$value) {
if(is_array($value)) { //Custom handling for arrays
if($is_list) $parts[] = array2json($value); /* :RECURSION: */
else $parts[] = ‘”‘ . $key . ‘”:’ . array2json($value); /* :RECURSION: */
} else {
$str = ”;
if(!$is_list) $str = ‘”‘ . $key . ‘”:’;

//Custom handling for multiple data types
if(is_numeric($value)) $str .= $value; //Numbers
elseif($value === false) $str .= ‘false’; //The booleans
elseif($value === true) $str .= ‘true’;
else $str .= ‘”‘ . addslashes($value) . ‘”‘; //All other things
// :TODO: Is there any more datatype we should be in the lookout for? (Object?)

$parts[] = $str;
}
}
$json = implode(‘,’,$parts);

if($is_list) return ‘[' . $json . ']‘;//Return numerical JSON
return ‘{‘ . $json . ‘}’;//Return associative JSON
}

This article is taken from http://www.bin-co.com/php/scripts/array2json/

Cross Domain Ajax Call

Method : JSONP

Description :  Are you looking for the code that will call file of other server than you are at right place just follow below instruction step by step it will work for you .

Steps :

1] Create one javascript function name it as “AjaxCallForOtherDomain”.

function AjaxCallForOtherDomain()

{

               var ajax_file_url = http://www.otherdomain.com/ajax/callme.php;

               var params = “&id=5”;

               $.getJSON(ajax_file_url+params+"&jsoncallback=?",    function(data){

               $('#placeholder').append(data.resultdata);

              });

}

** ajax_file_url is the web file url that we suppose to call.

** params is the variable that we are going to pass in php files.

** jsoncallback is the variable that will be dynamically assigned by “getJSON” function so you will get parameter “jsoncallback” parameter that will be function while you respond in PHP file.

** placeholder is the id where i will append my result from that is response from server file.

** data is JSON array.

** data.resultdata : Here result data is node of data array. E.g. : $data[‘resultdata’];

2] Create one PHP file on other domain inside ajax folder. 

Suppose you have created the file on www.otherdomain.com/publichtml/ajax/callme.php

<?php

$ jsoncallback = $_REQUEST[‘jsoncallback’];

echo  $ jsoncallback.”( {" resultdata’": "sudhirstiwari"} )”;
Exit;

?>

3] Handle the call in your javascript function inside the response.

$.getJSON(ajax_file_url+params+"&jsoncallback=?",    function(data){

// example of what is received from the server...

$(‘#placeholder’).append(data.resultdata);

});

That’s it :)
Its very easy so let me know if you have any queries regarding this .
Have a good luck…



How to Install BuddyPress ?

This is very common question while people are thinking to make their site as networking site. Its very easy but if you are developer and trying to install buddy press on your localhost then make sure of enabling “rewrite_module” “htaccess” otherwise it won’t work at your localhost.

Integrate live video streaming in his client’s website

Hi CMS Guru,

Nice to see you at Help Desk…

I want to integrate live video streaming in my website …

Can you Please suggests me steps to follow?

How to setup multi-store in Opencart

This intruction is based on my experience. You may find a different way. The steps are as follows:

In CPanel

Go to your CPanel,
Open Domain > SubDomain,
Fill in the subdomain input filed, such as: mobile (my second store will be http://opencart.techphpexpert.com),
Look at Directory Root input field, CPanel will fill it automatically. Don’t use it,.. Replace with your main store’s OpenCart installation folder. In my case /public_html/shop. Click Create.
In OpenCart Administration

Go to System > Settings,
Click Create A New Store button,
Fill in all required fields including the logo, favicon, etc.
In Store URL, fill it with http://opencart.techphpexpert.com,
Click Save
Done!!
Don’t forget to edit Category, Product, Manufacture, and Information Pages that you want to be displayed in your second store.

Important Notice : In your configuration file there is “/” added in selecting store query. so you must have to remove that for above to work.

source:stackoverflow.com
Hire Me
Follow Me!
Search
Most Popular Articles & Pages
Because your vote is Important
Sorry, there are no polls available at the moment.
Categories