Thursday, August 15, 2013

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.
                        )

                )

        )

)

Php create/edit eWay token for further payment

<?php
function 
create_token_eway()
{
    
$testUrl "https://www.eway.com.au/gateway/ManagedPaymentService/test/managedCreditCardPayment.asmx";
    
$liveUrl "https://www.eway.com.au/gateway/ManagedPaymentService/managedCreditCardPayment.asmx";
  
    
$eWaySOAPActionURL    "https://www.eway.com.au/gateway/managedpayment";
    
$eWayCustomerId       "87654321";
    
/* test account */
    
$eWayCustomerEmail    "test@eway.com.au";
    
/* test email */
    
$eWayCustomerPassword "test123";
    
/* test password */
  
    
$updateCustomer false;
    
$customTag      "CreateCustomer";
    
/* For update customer: "UpdateCustomer". */
    /**
     * If you want to update existing customer do the following -
     */
    
if ($updateCustomer) {
        
$updateCustomerEWayId "9876543211000";
        
/* Already saved customer id. */
        
$customTag            "UpdateCustomer";
        
$updateCustomerEWayId "<managedCustomerID>"  

              $updateCustomerEWayId 
              "</managedCustomerID>";
    }
  
    
$directXML "<?xml version=\"1.0\" encoding=\"utf-8\"?>
        <soap12:Envelope 

            xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
            xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"
            xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">
            <soap12:Header>
            <eWAYHeader xmlns=\"" 
$eWaySOAPActionURL "\">
                <eWAYCustomerID>" 
$eWayCustomerId "</eWAYCustomerID>
                <Username>" 
$eWayCustomerEmail "</Username>
                <Password>" 
$eWayCustomerPassword "</Password>
            </eWAYHeader>
        </soap12:Header>
          <soap12:Body>
            <" 
$customTag " xmlns=\"" $eWaySOAPActionURL "\">
                " 
$updateCustomerEWayId "
                <Title>Mr.</Title>
                <FirstName>Pritom</FirstName>
                <LastName>Kumar Mondal</LastName>
                <Address></Address>
                <Suburb></Suburb>
                <State></State>
                <Company>Khulna University</Company>
                <PostCode></PostCode>
                <Country>au</Country>
                <Email>pritomkucse@gmail.com</Email>
                <Fax></Fax>
                <Phone></Phone>
                <Mobile></Mobile>
                <CustomerRef>CSE-060238</CustomerRef>
                <JobDesc></JobDesc>
                <Comments></Comments>
                <URL></URL>
                <CCNumber>4444333322221111</CCNumber>
                <CCNameOnCard>Pritom K Mondal</CCNameOnCard>
                <CCExpiryMonth>12</CCExpiryMonth>
                <CCExpiryYear>15</CCExpiryYear>
            </" 
$customTag ">
        </soap12:Body>
        </soap12:Envelope>"
;
  
    
$result makeCurlCall(

    $testUrl/* CURL URL */ 
    "POST"/* CURL CALL METHOD */  
    array(
        
/* CURL HEADERS */
        
"Content-Type: text/xml; charset=utf-8",
        
"Accept: text/xml",
        
"Pragma: no-cache",
        
"SOAPAction: " $eWaySOAPActionURL "/" $customTag,
        
"Content_length: " strlen(trim($directXML))
    ), 

    null/* CURL GET PARAMETERS */  
    $directXML /* CURL POST PARAMETERS AS XML */ );
  
    if (
$result != null && isset($result["response"])) {
        echo 
$result["response"]; /* Result printed below */
    }
    die(
"");
}
 


/* makeCurlCall */ 
function makeCurlCall($url$method "GET"$headers null$gets null$posts null)
{
    
$ch curl_init();
    if (
$gets != null) {
        
$url .= "?" . (http_build_query($gets));
    }
    
curl_setopt($chCURLOPT_URL$url);
    
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
    
curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
  
    if (
$posts != null) {
        
curl_setopt($chCURLOPT_POSTFIELDS$posts);
    }
    if (
$method == "POST") {
        
curl_setopt($chCURLOPT_POSTtrue);
    } else if (
$method == "PUT") {
        
curl_setopt($chCURLOPT_CUSTOMREQUEST"PUT");
    } else if (
$method == "HEAD") {
        
curl_setopt($chCURLOPT_NOBODYtrue);
    }
    if (
$headers != null && is_array($headers)) {
        
curl_setopt($chCURLOPT_HTTPHEADER$headers);
    }
    
$response curl_exec($ch);
    
$code     curl_getinfo($chCURLINFO_HTTP_CODE);
  
    
curl_close($ch);
    return array(
        
"code" => $code,
        
"response" => $response
    
);
}
 

create_token_eway();?>

Output

<?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:Envelope>

Tuesday, August 13, 2013

PHP QR Code Generator Class

Here is the PHP QR code generator class that creates PNG QR code images from text. The class will create various QR code types like text, URLs, emails, etc:
BarcodeQR.zip.

Requirements: PHP Web server and cURL Library (client URL).

The PHP QR code class will create a PNG QR code image or save a PNG QR code image file, here is an example:// include BarcodeQR class 
include 
"BarcodeQR.php"; 
// set BarcodeQR object 
$qr 
= new BarcodeQR(); 
// create URL QR code 
$qr
->url("Pritom K Mondal"); 
// display new QR code image 
$qr
->draw();
This example will create and display this QR code image:









You can also save the QR code PNG image like this: // save new QR code image (size 150x150) 
$qr
->draw(150, "tmp/qr-code.png");
Other QR code types the class will create:// bookmark 
$qr
->bookmark("title", "url"); 
// contact 
$qr
->contact("name", "address", "phone", "email"); 
// content 
$qr
->content("type", "size", "content"); 
// email 
$qr
->email("email", "subject", "message"); 
// geo location 
$qr
->geo("lat", "lon", "height"); 
// phone 
$qr
->phone("phone"); 
// sms 
$qr
->sms("phone", "text"); 
// text 
$qr
->text("text"); 
// URL 
$qr
->url("url"); 
// wifi connection 
$qr
->wifi("type", "ssid", "password");
http://www.shayanderson.com/php/php-qr-code-generator-class.htm

Monday, August 12, 2013

PHP Barcode Generator

Here is an easy to use PHP barcode generator class.
Requirements: PHP Web server and GD Library (Graphics Library).

The PHP class will create a GIF barcode image or save a GIF barcode image file, here is an example:// include Barcode39 class 
include 
"BarCode.php"; 
// set Barcode39 object 
$bc 
= new Barcode39("AB3740-45"); 
// display new barcode 
$bc
->draw();
This example will output this barcode:






You can also easily adjust the barcode bar sizes and text size:// set object 
$bc 
= new BarCode("AB33740-45"); 
// set text size 
$bc
->barcode_text_size = 5; 
// set barcode bar thickness (thick bars) 
$bc
->barcode_bar_thick = 4; 
// set barcode bar thickness (thin bars) 
$bc
->barcode_bar_thin = 2; 
// save barcode GIF file 
$bc
->draw("barcode.gif");
This example will save this barcode as "barcode.gif": 





http://www.shayanderson.com/php/php-barcode-generator-class-code-39.htm