Monday, August 19, 2013

How can I upload files asynchronously with jQuery


With HTML5 you CAN make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME-type) or handle the progress eventwith the HTML5 progress tag (or a div).

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<form enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>

<div class="progress_bar"
     style="width: 300px; height: 20px; background-color: blue; position: relative;">
    <div class="full" style="width: 0%;
    height: 20px; background-color: red;"></div>
    <div class="text"
         style="color: #ffffff; font-weight: bold; text-align: center;
         position: absolute; left: 109px; top: 0;">Uploading...</div>
</div>
<script type="text/javascript">
    jQuery(document).ready(function() {
        $(':button').click(function(){
            var formData = new FormData($('form')[0]);
            $.ajax({
                url: 'upload.php',  //Server script to process data
                type: 'POST',
                xhr: function() {  // Custom XMLHttpRequest
                    var myXhr = $.ajaxSettings.xhr();
                    if(myXhr.upload){ // Check if upload property exists
                        myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
                    }
                    return myXhr;
                },
                //Ajax events
                beforeSend: function() {
                    console.log("Before send...");
                    var $div = jQuery("div.progress_bar");
                    $div.find("div.full").css({
                        width: "0%"
                    });
                },
                success: function(data) {
                    console.log(data);
                    console.log("Success...");
                    var $div = jQuery("div.progress_bar");
                    $div.find("div.text").html("Uploaded.");
                },
                error: function() {
                    console.log("Error...");
                },
                // Form data
                data: formData,
                //Options to tell jQuery not to process data or worry about content-type.
                cache: false,
                contentType: false,
                processData: false
            });
        });
    });
    function progressHandlingFunction(e){
        console.log(e);
        if(e.lengthComputable){
            var $div = jQuery("div.progress_bar");
            var p = e.loaded / e.total * 100;
            $div.find("div.full").css({
                width: p + "%"
            });
            console.log(p);
        }
    }
</script>


As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser. 

Downloading a Remote File With cURL and PHP

cURL is a great tool to help you connect to remote web sites, making it easy to post forms, retrieve web pages, or even to download files. In this PhpRiot Snippet I'll show you how you can download a file straight to disk using cURL.
Note: To simplify our key points in this article we don't perform any error checking on the cURL requests. You should always do so; the curl_getinfo function is extremely useful for this.
If you use basic options when executing a cURL request, the returned data will be output directly. If instead you want to assign the response to a PHP variable you would specify the CURLOPT_RETURNTRANSFER option.
You can then read the response and write it to disk, as shown in the following listing. The $path variable is the location on the server where you want to write the file.
Listing 1 Downloading a file and saving it with file_put_contents() (listing-1.php)
<?php 
    set_time_limit(0); 
    $url  = 'http://www.example.com/a-large-file.zip';
    $path = '/path/to/a-large-file.zip';
 
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
    $data = curl_exec($ch);
 
    curl_close($ch);
 
    file_put_contents($path, $data);
?>
There is however a problem with this code. If the file you're downloading is quite large, the entire contents must be read into memory before being written to disk. Doing so can result in your script breaking down due to exceeding the memory limit.
Note: Even if your memory limit is set extremely high, you would be putting unnecessary strain on your server by reading in a large file straight to memory.
Therefore, you should let cURL do the hard work by passing to it a writable file stream. You can do this using the CURLOPT_FILE option.
Note: Because we'll be writing to a file you no longer specify the CURLOPT_RETURNTRANSFER option.
To do this you must first create a new file pointer using fopen(). Next we pass this file pointer to cURL and perform the request. Finally, we close the file pointer.
Listing 2 Using cURL to download straight to a file stream (listing-2.php)
<?php     
    set_time_limit(0); 
    $url  = 'http://www.example.com/a-large-file.zip';
    $path = '/path/to/a-large-file.zip';
 
    $fp = fopen($path, 'w');
 
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
 
    $data = curl_exec($ch);
 
    curl_close($ch);
    fclose($fp);
?>
That's all there is to it. You can now download files without worrying about exceeding PHP's memory limit.

PHP Script to force download big files using chunk

<?php
$file 
dirname(__FILE__) . "/download_it.zip";
if (
file_exists($file)) {
    if (
FALSE !== ($handler fopen($file'r'))) {
        
header('Content-Description: File Transfer');
        
header('Content-Type: application/octet-stream');
        
header('Content-Disposition: attachment; filename=' basename($file));
        
header('Content-Transfer-Encoding: chunked'); //changed to chunked
        
header('Expires: 0');
        
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        
header('Pragma: public');
      
        
//Send the content in chunks
        
while (false !== ($chunk fread($handler4096))) {
            echo 
$chunk;
        }
    }
    exit;
}
echo 
"<h1>Content error</h1><p>The file does not exist!</p>";?>

Thursday, August 15, 2013

Save PHP Array Data as Formatted XML and Parse Again

<?php 
include 'xml_converter.class.php'; /* Download class file */

include 'xml.class.php';           /* Download class file */
 

/* Your array of data */ 
$data = array(
    
'first_name' => 'Pritom',
    
'middle_name' => "Kumar",
    
'last_name' => 'Mondal',
    
'url' => 'http://pritomkumar.blogspot.com',
    
'languages' => array(
        
'php language !! ' => '<!CDATA[&Php&amp;]]>%♣♠♥♦◊〉〈 ⌋ ⌊ ⌈ ⌉ ⋮ ⋅ ⊥ ⊗ ⊕ ⊇',
        
'Java Script ⊆ ⊄ ⊃ ⊂ ≥ ≤ ≡ ≠ ≈ ≅ ∼ ∴ ∫ ∪ ∩ ∨',
        
'Java ∧ ∠ ∞ ∝ √ ∗ − ∑ ∏ ∋ ∉ ∈ ∇ ∅ ∃ ∂ ∀ ⇔ ⇓ ⇒ ⇑ ⇐',
        
'CSS',
        
"CakePhp<Help]>]]\/\/\/\/\/\/",
        
"jQuery"
    
),
    
'title' => 'Pritom Kumar (Web Developer)',
    
"inline_tag" => "<name><first>Pritom</first><last>Kumar</last></name>",
    
'favorite_blogs' => array(
        
'CSSTricks' => 'http://css-tricks.com',
        
'AJAXian' => 'http://ajaxian.com'
    
),
    
"invalid characters" => array(
        
"''" => "00-&*",
        
"'" => "&#39;",
        
">" => "&#62;",
        
"<" => "&#60;",
        
"&" => "&#38;",
        
"-" => "&#45;",
        
"°" => "&#176;"
    
)
);

 /* Array to xml converting... */ 

$xmlConverter = new XmlConverter($data); 

$xmlString    $xmlConverter->toXmlString();

/* Xml would look like this: */ 
echo $xmlString;


<?xml version="1.0" encoding="UTF-8"?>
<data>
   <first_name><![CDATA[Pritom]]></first_name>
   <middle_name><![CDATA[Kumar]]></middle_name>
   <last_name><![CDATA[Mondal]]></last_name>
   <url><![CDATA[http://pritomkumar.blogspot.com]]></url>
   <languages>
      <php_language____><![CDATA[<!CDATA[&Php&amp;]]&gt;%♣♠♥♦◊⟩⟨ ⌋ ⌊ ⌈ ⌉ ⋮ ⋅ ⊥ ⊗ ⊕ ⊇]]></php_language____>
      <tag_0><![CDATA[Java Script ⊆ ⊄ ⊃ ⊂ ≥ ≤ ≡ ≠ ≈ ≅ ∼ ∴ ∫ ∪ ∩ ∨]]></tag_0>
      <tag_1><![CDATA[Java ∧ ∠ ∞ ∝ √ ∗ − ∑ ∏ ∋ ∉ ∈ ∇ ∅ ∃ ∂ ∀ ⇔ ⇓ ⇒ ⇑ ⇐]]></tag_1>
      <tag_2><![CDATA[CSS]]></tag_2>
      <tag_3><![CDATA[CakePhp<Help]>]]\/\/\/\/\/\/]]></tag_3>
      <tag_4><![CDATA[jQuery]]></tag_4>
   </languages>
   <title><![CDATA[Pritom Kumar (Web Developer)]]></title>
   <inline_tag><![CDATA[<name><first>Pritom</first><last>Kumar</last></name>]]></inline_tag>
   <favorite_blogs>
      <CSSTricks><![CDATA[http://css-tricks.com]]></CSSTricks>
      <AJAXian><![CDATA[http://ajaxian.com]]></AJAXian>
   </favorite_blogs>
   <invalid_characters>
      <tag___><![CDATA[00-&*]]></tag___>
      <tag__><![CDATA[&#39;]]></tag__>
      <tag__><![CDATA[&#62;]]></tag__>
      <tag__><![CDATA[&#60;]]></tag__>
      <tag__><![CDATA[&#38;]]></tag__>
      <tag__><![CDATA[&#45;]]></tag__>
      <tag___><![CDATA[&#176;]]></tag___>
   </invalid_characters>
</data>


/* After parse xml, array would look like this: */ 

$xmlParser = new XmlToArrayParser($xmlString);

print_r($xmlParser); 

xmlToArrayParser Object
(
    [array] => Array
        (
            [data] => Array
                (
                    [first_name] => Pritom
                    [middle_name] => Kumar
                    [last_name] => Mondal
                    [url] => http://pritomkumar.blogspot.com
                    [languages] => Array
                        (
                            [php_language____] => <!CDATA[&Php&amp;]]&gt;%♣♠♥♦◊〉〈 ⌋ ⌊ ⌈ ⌉ ⋮ ⋅ ⊥ ⊗ ⊕ ⊇
                            [tag_0] => Java Script ⊆ ⊄ ⊃ ⊂ ≥ ≤ ≡ ≠ ≈ ≅ ∼ ∴ ∫ ∪ ∩ ∨
                            [tag_1] => Java ∧ ∠ ∞ ∝ √ ∗ − ∑ ∏ ∋ ∉ ∈ ∇ ∅ ∃ ∂ ∀ ⇔ ⇓ ⇒ ⇑ ⇐
                            [tag_2] => CSS
                            [tag_3] => CakePhp<Help]>]]\/\/\/\/\/\/
                            [tag_4] => jQuery
                        )

                    [title] => Pritom Kumar (Web Developer)
                    [inline_tag] => <name><first>Pritom</first><last>Kumar</last></name>
                    [favorite_blogs] => Array
                        (
                            [CSSTricks] => http://css-tricks.com
                            [AJAXian] => http://ajaxian.com
                        )

                    [invalid_characters] => Array
                        (
                            [tag___] => Array
                                (
                                    [0] => 00-&*
                                    [1] => &#176;
                                )

                            [tag__] => Array
                                (
                                    [0] => &#39;
                                    [1] => &#62;
                                    [2] => &#60;
                                    [3] => &#38;
                                    [4] => &#45;
                                )

                        )

                )

        )

    [parse_error] =>
    [parser:xmlToArrayParser:private] => Resource id #4
    [pointer:xmlToArrayParser:private] => Array
        (
            [data] => Array
                (
                    [first_name] => Pritom
                    [middle_name] => Kumar
                    [last_name] => Mondal
                    [url] => http://pritomkumar.blogspot.com
                    [languages] => Array
                        (
                            [php_language____] => <!CDATA[&Php&amp;]]&gt;%♣♠♥♦◊〉〈 ⌋ ⌊ ⌈ ⌉ ⋮ ⋅ ⊥ ⊗ ⊕ ⊇
                            [tag_0] => Java Script ⊆ ⊄ ⊃ ⊂ ≥ ≤ ≡ ≠ ≈ ≅ ∼ ∴ ∫ ∪ ∩ ∨
                            [tag_1] => Java ∧ ∠ ∞ ∝ √ ∗ − ∑ ∏ ∋ ∉ ∈ ∇ ∅ ∃ ∂ ∀ ⇔ ⇓ ⇒ ⇑ ⇐
                            [tag_2] => CSS
                            [tag_3] => CakePhp<Help]>]]\/\/\/\/\/\/
                            [tag_4] => jQuery
                        )

                    [title] => Pritom Kumar (Web Developer)
                    [inline_tag] => <name><first>Pritom</first><last>Kumar</last></name>
                    [favorite_blogs] => Array
                        (
                            [CSSTricks] => http://css-tricks.com
                            [AJAXian] => http://ajaxian.com
                        )

                    [invalid_characters] => Array
                        (
                            [tag___] => Array
                                (
                                    [0] => 00-&*
                                    [1] => &#176;
                                )

                            [tag__] => Array
                                (
                                    [0] => &#39;
                                    [1] => &#62;
                                    [2] => &#60;
                                    [3] => &#38;
                                    [4] => &#45;
                                )

                        )

                )

        )

)


?>

Read an Excel file from PHP

Download Library.

Creating The Reader Object

$data = new Spreadsheet_Excel_Reader("test.xls");
Or conserve memory for large worksheets by not storing the extended information about cells like fonts, colors, etc.
$data = new Spreadsheet_Excel_Reader("test.xls",false);
To use a coding other than UTF-8 (default) you can pass it as the 3rd parameter.
$data = new Spreadsheet_Excel_Reader("test.xls",true,"UTF-16");

Dumping Worksheet Contents

The simplest way to interact with an XLS file is to just dump it to HTML for display in a browser. This method will generate a table with inline CSS and all available formatting.
$data->dump($row_numbers=false,$col_letters=false,$sheet=0,$table_class='excel')

Accessing Cell Values

It is recommended that the public API functions be used to access data rather than relying on the underlying data structure, which may change between releases.
Retrieve the formatted value of a cell (what is displayed by Excel) on the first (or only) worksheet:
$data->val($row,$col)
You can also use column names rather than numbers:
$data->val(10,'AZ')
Access data on a different sheet:
$data->val($row,$col,$sheet_index)

Sheet Info

Get the count of how many rows/cols are on a sheet (default: first sheet):
$data->rowcount($sheet_index=0) $data->colcount($sheet_index=0)

Cell Info

The type of data in the cell: number|date|unknown
$data->type($row,$col,$sheet=0)
The raw data stored for the cell. For example, a cell may contain 123.456 but display as 123.5 because of the cell's format. Raw accesses the underlying value.
$data->raw($row,$col,$sheet=0)
If the cell has a hyperlink associated with it, the url can be retrieved.
$data->hyperlink($row,$col,$sheet=0)
Rowspan/Colspan of the cell.
$data->rowspan($row,$col,$sheet=0) $data->colspan($row,$col,$sheet=0)

Example

Microsoft Excel Screenshot

 

















PHP Output

By simply using this php command:
<?php echo $data->dump(true,true); ?>
The output looks like this (with some CSS):




















https://code.google.com/p/php-excel-reader/wiki/Documentation 

Wednesday, August 14, 2013

How to parse XML with php code which contains namespace, cdata, ampersand

Download xml.class.php

Php code to parse xml which contains namespace, cdata and ampersand symbol included


<?php
class XmlToArrayParser {
    /** The array created by the parser can be assigned to any variable: $anyVarArr = $domObj->array.*/
    public $array = array();
    private $parse_error = false;
    private $parser;
    private $pointer;

    /** Constructor: $domObj = new xmlToArrayParser($xml); */
    public function __construct($xml) {
        $xml = str_replace(array('&'), array('&amp;'), $xml);
        $this->pointer =& $this->array;
        $this->parser = xml_parser_create("UTF-8");
        xml_set_object($this->parser, $this);
        xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
        xml_set_element_handler($this->parser, "tag_open", "tag_close");
        xml_set_character_data_handler($this->parser, "cdata");
        $this->parse_error = xml_parse($this->parser, ltrim($xml)) ? false : true;
    }

    /** Free the parser. */
    public function __destruct() {
        xml_parser_free($this->parser);
    }

    /** Get the xml error if an an error in the xml file occured during parsing. */
    public function get_xml_error() {
        if ($this->parse_error) {
            $errCode = xml_get_error_code($this->parser);
            $thisError = "Error Code [" . $errCode . "] \"<strong style='color:red;'>" . xml_error_string($errCode) . "</strong>\",
                            at char " . xml_get_current_column_number($this->parser) . "
                            on line " . xml_get_current_line_number($this->parser) . "";
        } else {
            $thisError = $this->parse_error;
        }
        return $thisError;
    }

    private function tag_open($parser, $tag, $attributes) {
        $this->convert_to_array($tag, 'attrib');
        $idx = $this->convert_to_array($tag, 'cdata');
        if (isset($idx)) {
            $this->pointer[$tag][$idx] = Array(
                '@idx' => $idx,
                '@parent' => &$this->pointer
            );
            $this->pointer =& $this->pointer[$tag][$idx];
        } else {
            $this->pointer[$tag] = Array(
                '@parent' => &$this->pointer
            );
            $this->pointer =& $this->pointer[$tag];
        }
        if (!empty($attributes)) {
            $this->pointer['attrib'] = $attributes;
        }
    }

    /** Adds the current elements content to the current pointer[cdata] array. */
    private function cdata($parser, $cdata) {
        if (strlen(trim($cdata)) > 0) {
            if (isset($this->pointer['cdata'])) {
                $this->pointer['cdata'] .= $cdata;
            } else {
                $this->pointer['cdata'] = $cdata;
            }
        }
    }

    private function tag_close($parser, $tag) {
        $current =& $this->pointer;
        if (isset($this->pointer['@idx'])) {
            unset($current['@idx']);
        }

        $this->pointer =& $this->pointer['@parent'];
        unset($current['@parent']);

        if (isset($current['cdata']) && count($current) == 1) {
            $current = $current['cdata'];
        } else if (empty($current['cdata'])) {
            unset($current['cdata']);
        }
    }

    /** Converts a single element item into array(element[0]) if a second element of the same name is encountered. */
    private function convert_to_array($tag, $item) {
        if (isset($this->pointer[$tag][$item])) {
            $content = $this->pointer[$tag];
            $this->pointer[$tag] = array(
                (0) => $content
            );
            $idx = 1;
        } else if (isset($this->pointer[$tag])) {
            $idx = count($this->pointer[$tag]);
            if (!isset($this->pointer[$tag][0])) {
                foreach ($this->pointer[$tag] as $key => $value) {
                    unset($this->pointer[$tag][$key]);
                    $this->pointer[$tag][0][$key] = $value;
                }
            }
        } else {
            $idx = null;
        }
        return $idx;
    }
}
?>

Parsing XML example


<?php
$xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\"
    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
    xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
    <soap:Body>
        <CreateCustomerResponse xmlns=\"https://www.eway.com.au/gateway/managedpayment\">
            <CreateCustomerResult>9876543211000</CreateCustomerResult>
        </CreateCustomerResponse>
    </soap:Body>
    <soap:Body>
        <CreateCustomerResponse xmlns=\"https://www.eway.com.au/gateway/managedpayment\">
            <CreateCustomerResult>9876543211000</CreateCustomerResult>
        </CreateCustomerResponse>
    </soap:Body>
    <address name=\"pritom\">
        <actual content=\"Pritom Kumar\"/>
        <forward forwarding=\"yes\" content=\"pritom\">Forward to pritom & else one</forward>
        <response responding=\"yes\"><![CDATA[Thanks you.]]></response>
    </address>
</soap:Envelope>";

echo "<pre>";
$xmlObject = new XmlToArrayParser($xmlString);
print_r($xmlObject->array);
echo "</pre>";
?>

Output


Array
(
    [soap:Envelope] => Array
        (
            [attrib] => Array
                (
                    [xmlns:soap] => http://www.w3.org/2003/05/soap-envelope
                    [xmlns:xsi] => http://www.w3.org/2001/XMLSchema-instance
                    [xmlns:xsd] => http://www.w3.org/2001/XMLSchema
                )

            [soap:Body] => Array
                (
                    [0] => Array
                        (
                            [CreateCustomerResponse] => Array
                                (
                                    [attrib] => Array
                                        (
                                            [xmlns] => https://www.eway.com.au/gateway/managedpayment
                                        )

                                    [CreateCustomerResult] => 9876543211000
                                )

                        )

                    [1] => Array
                        (
                            [CreateCustomerResponse] => Array
                                (
                                    [attrib] => Array
                                        (
                                            [xmlns] => https://www.eway.com.au/gateway/managedpayment
                                        )

                                    [CreateCustomerResult] => 9876543211000
                                )

                        )

                )

            [address] => Array
                (
                    [attrib] => Array
                        (
                            [name] => pritom
                        )

                    [actual] => Array
                        (
                            [attrib] => Array
                                (
                                    [content] => Pritom Kumar
                                )

                        )

                    [forward] => Array
                        (
                            [attrib] => Array
                                (
                                    [forwarding] => yes
                                    [content] => pritom
                                )

                            [cdata] => Forward to pritom & else one
                        )

                    [response] => Array
                        (
                            [attrib] => Array
                                (
                                    [responding] => yes
                                )

                            [cdata] => Thanks you.
                        )

                )

        )

)