Sign up to create your own snipts, or login.

Public snipts » robertbanh's snipts » php The latest php snipts from robertbanh.

showing 1-19 of 19 snipts for php
  • Truncate Strings
    <?php
    
    // truncate with smart check for spaces
    function truncate($string, $limit = 75, $break = " ", $pad = "...") 
    {
        if (strlen($string) <= $limit) return $string; 
        
        $string = substr($string, 0, $limit); 
        if (false !== ($breakpoint = strrpos($string, $break))) 
        {
            $string = substr($string, 0, $breakpoint);
        }
        return $string . $pad; 
    }
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Mar 02, 2010 at 10:23 a.m. EST
  • PHP Array to XML (with attributes)
    <?php
    //
    /*
        Example usage:
        ===============
        $xml = "
        <library id='123' test='456'>
            <book>
                <authorFirst>Mark</authorFirst>
                <authorLast>Twain</authorLast>
                <title>The Innocents Abroad</title>
            </book>
            <book>
                <authorFirst>Charles</authorFirst>
                <authorLast>Dickens</authorLast>
                <title>Oliver Twist</title>
            </book>
        </library>";
        
        echo "<pre>";
        var_export(ArrayToXML::xml2array($xml));
        ===============
        
        $library = array(
            'library' => array(
                '_a' => array( 'id'=>'1234', 'test'=>'456' ),
                '_c' => array( 'book' => array(
                    '_c' => array(
                        'authorFirst' => array( '_v' => 'Mark' ),
                        'authorLast'  => array( '_v' => 'Twain' ),
                        'title'       => array( '_v' => 'The Innocents Abroad' )
                        ),
                    '_c' => array(
                        'authorFirst' => array( '_v' => 'Charles' ),
                        'authorLast'  => array( '_v' => 'Dickens' ),
                        'title'       => array( '_v' => 'Oliver Twist' )
                        ),
                    )
                )
            )
        );
        header('Content-Type: application/xml');
        echo ArrayToXML::array2xml($library);
        
    */
    class ArrayToXML
    {
        // Array to XML
        public static function array2xml($cary, $d=0, $forcetag='') {
            $res=array();
            foreach ($cary as $tag=>$r) {
                if (isset($r[0])) {
                    $res[]=ArrayToXML::array2xml($r, $d, $tag);
                } else {
                    if ($forcetag) $tag=$forcetag;
                    $sp=str_repeat("\t", $d);
                    $res[]="$sp<$tag";
                    if (isset($r['_a'])) {foreach ($r['_a'] as $at=>$av) $res[]=" $at=\"$av\"";}
                    $res[]=">".((isset($r['_c'])) ? "\n" : '');
                    if (isset($r['_c'])) $res[]=ArrayToXML::array2xml($r['_c'], $d+1);
                    elseif (isset($r['_v'])) $res[]=$r['_v'];
                    $res[]=(isset($r['_c']) ? $sp : '')."</$tag>\n";
                }
                
            }
            return implode('', $res);
        }
        
        // XML to Array
        public static function xml2array(&$string) {
            $parser = xml_parser_create();
            xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
            xml_parse_into_struct($parser, $string, $vals, $index);
            xml_parser_free($parser);
    
            $mnary=array();
            $ary=&$mnary;
            foreach ($vals as $r) {
                $t=$r['tag'];
                if ($r['type']=='open') {
                    if (isset($ary[$t])) {
                        if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
                        $cv=&$ary[$t][count($ary[$t])-1];
                    } else $cv=&$ary[$t];
                    if (isset($r['attributes'])) {foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;}
                    $cv['_c']=array();
                    $cv['_c']['_p']=&$ary;
                    $ary=&$cv['_c'];
    
                } elseif ($r['type']=='complete') {
                    if (isset($ary[$t])) { // same as open
                        if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
                        $cv=&$ary[$t][count($ary[$t])-1];
                    } else $cv=&$ary[$t];
                    if (isset($r['attributes'])) {foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;}
                    $cv['_v']=(isset($r['value']) ? $r['value'] : '');
    
                } elseif ($r['type']=='close') {
                    $ary=&$ary['_p'];
                }
            }    
            
            ArrayToXML::_del_p($mnary);
            return $mnary;
        }
    
        // _Internal: Remove recursion in result array
        public static function _del_p(&$ary) {
            foreach ($ary as $k=>$v) {
                if ($k==='_p') unset($ary[$k]);
                elseif (is_array($ary[$k])) ArrayToXML::_del_p($ary[$k]);
            }
        }
        
        // Insert element into array
        public static function ins2ary(&$ary, $element, $pos) {
            $ar1=array_slice($ary, 0, $pos); $ar1[]=$element;
            $ary=array_merge($ar1, array_slice($ary, $pos));
        }
    }
    }
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Feb 24, 2010 at 2:17 p.m. EST
  • PHP Array to XML
    <?php
    //
    // 
    /*
        Example usage:
        ===============
        <library>
            <book>
                <authorFirst>Mark</authorFirst>
                <authorLast>Twain</authorLast>
                <title>The Innocents Abroad</title>
            </book>
            <book>
                <authorFirst>Charles</authorFirst>
                <authorLast>Dickens</authorLast>
                <title>Oliver Twist</title>
            </book>
        </library>
        
        =================
        $library = array(
            'book' => array(
                array(
                    'authorFirst' => 'Mark',
                    'authorLast' => 'Twain',
                    'title' => 'The Innocents Abroad'
                ),
                array(
                    'authorFirst' => 'Charles',
                    'authorLast' => 'Dickens',
                    'title' => 'Oliver Twist'
                )
            )
        );
        header('Content-Type: application/xml');
        echo ArrayToXML::toXML($library, 'library');
    */
    
        
    class ArrayToXML
    {
        /**
         * The main function for converting to an XML document.
         * Pass in a multi dimensional array and this recrusively loops through and builds up an XML document.
         *
         * @param array $data
         * @param string $rootNodeName - what you want the root node to be - defaultsto data.
         * @param SimpleXMLElement $xml - should only be used recursively
         * @return string XML
         */
        public static function toXML( $data, $rootNodeName = 'ResultSet', &$xml=null ) {
    
            // turn off compatibility mode as simple xml throws a wobbly if you don't.
            if ( ini_get('zend.ze1_compatibility_mode') == 1 ) ini_set ( 'zend.ze1_compatibility_mode', 0 );
            if ( is_null( $xml ) ) //$xml = simplexml_load_string( "" );
                $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$rootNodeName />");
    
            // loop through the data passed in.
            foreach( $data as $key => $value ) {
    
                $numeric = false;
                
                // no numeric keys in our xml please!
                if ( is_numeric( $key ) ) {
                    $numeric = 1;
                    $key = $rootNodeName;
                }
    
                // delete any char not allowed in XML element names
                $key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key);
    
                // if there is another array found recrusively call this function
                if ( is_array( $value ) ) {
                    $node = ArrayToXML::isAssoc( $value ) || $numeric ? $xml->addChild( $key ) : $xml;
    
                    // recrusive call.
                    if ( $numeric ) $key = 'anon';
                    ArrayToXML::toXml( $value, $key, $node );
                } else {
    
                    // add single node.
                    $value = htmlentities( $value );
                    $xml->addChild( $key, $value );
                }
            }
    
            // pass back as XML
            return $xml->asXML();
    
        // if you want the XML to be formatted, use the below instead to return the XML
            //$doc = new DOMDocument('1.0');
            //$doc->preserveWhiteSpace = false;
            //$doc->loadXML( $xml->asXML() );
            //$doc->formatOutput = true;
            //return $doc->saveXML();
        }
    
    
        /**
         * Convert an XML document to a multi dimensional array
         * Pass in an XML document (or SimpleXMLElement object) and this recrusively loops through and builds a representative array
         *
         * @param string $xml - XML document - can optionally be a SimpleXMLElement object
         * @return array ARRAY
         */
        public static function toArray( $xml ) {
            if ( is_string( $xml ) ) $xml = new SimpleXMLElement( $xml );
            $children = $xml->children();
            if ( !$children ) return (string) $xml;
            $arr = array();
            foreach ( $children as $key => $node ) {
                $node = ArrayToXML::toArray( $node );
    
                // support for 'anon' non-associative arrays
                if ( $key == 'anon' ) $key = count( $arr );
    
                // if the node is already set, put it into an array
                if ( isset( $arr[$key] ) ) {
                    if ( !is_array( $arr[$key] ) || $arr[$key][0] == null ) $arr[$key] = array( $arr[$key] );
                    $arr[$key][] = $node;
                } else {
                    $arr[$key] = $node;
                }
            }
            return $arr;
        }
    
        // determine if a variable is an associative array
        public static function isAssoc( $array ) {
            return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
        }
    }
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Feb 23, 2010 at 11:43 a.m. EST
  • Enable SOAP on Media Temple DV server
    # Navigate to a relatively unimportant directory. I chose /home/
    cd /home/
    
    # Download PHP (http://www.php.net/releases/)
    wget http://museum.php.net/php5/php-5.2.6.tar.gz
    
    # Unpack the PHP file
    tar -zxf php-5.2.6.tar.gz
    
    # Configure the new PHP to enable SOAP (will take a few minutes) (before enable is two dashes)
    cd php-5.2.6
    ./configure --enable-soap=shared
    
    # Rebuild PHP (this will also take a while)
    make
    
    # Copy just the SOAP module into your existing installation of PHP
    cp modules/soap.so /usr/lib/php/modules/
    
    # Add the new SOAP configuration to your existing configuration
    echo "extension=soap.so" > /etc/php.d/soap.ini
    
    # Restart Apache
    /etc/init.d/httpd restart
    
    # Optional: You can now delete /home/php-5.2.6/ if you’d like, as you won’t need it any longer.
    rm -rf /home/php-5.2.6/
    
    # Check phpinfo() to confirm that SOAP is now enabled.
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Feb 22, 2010 at 8:45 p.m. EST
  • Dates Samples
    <?php
    
    $currDate = date('Y-m-d h:i:s');
    
    // convert timestamp from mysql
    $nextReviewDt = date('F d, Y',strtotime($nextReviewDt));
    
    // Add 30 days 
    $CommentStartDt = date('m/d/Y');
    $CommentEndDt = date('m/d/Y', 
    	mktime(0,0,0,date("m"),date("d")+30,date("Y"))); // add 30 days
    
    // convert year to 4 digits
    if ($y > 60) $y = '19'.$y;
    else $y = '20'.$y;
    
    // split if there are slash or dash
    list($m, $d, $y) = split('[/|-]', $iDate);
    
    if (preg_match("/-/", $iDate))
    	list($m, $d, $y) = split('-', $iDate);
    else if (preg_match("/\//", $iDate))
    	list($m, $d, $y) = split('/', $iDate);
    
    $specDate = mktime(0, 0, 0, $m, $d, $y);
    $numOfDays = (time() - $specDate) / (24 * 60 * 60);
    
    // convert date from mysql db
    if (preg_match("/(.*)Dt$/", $dbDate))
    	$dbDate = date("M d, Y h:ia", strtotime($dbDate));
    
    // output dates - walk the days
    $startDt = '2009-01-04';
    $endDt = date('Y-m-d');
    while ($startDt != $endDt)
    {
    	echo "$startDt <br/>";
    	// increment the day
    	$startDt = strtotime(date("Y-m-d", strtotime($startDt)) . " +1 day");
    	// convert back to readable format
    	$startDt = date("Y-m-d",$startDt);
    }
    
    function count_days( $a, $b )
    {
    	// First we need to break these dates into their constituent parts:
    	$gd_a = getdate( $a );
    	$gd_b = getdate( $b );
    
    	// Now recreate these timestamps, based upon noon on each day
    	// The specific time doesn't matter but it must be the same each day
    	$a_new = mktime( 12, 0, 0, $gd_a['mon'], $gd_a['mday'], $gd_a['year'] );
    	$b_new = mktime( 12, 0, 0, $gd_b['mon'], $gd_b['mday'], $gd_b['year'] );
    
    	// Subtract these two numbers and divide by the number of seconds in a
    	//  day. Round the result since crossing over a daylight savings time
    	//  barrier will cause this time to be off by an hour or two.
    	return round( abs( $a_new - $b_new ) / 86400 );
    }
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Jan 22, 2010 at 3:28 p.m. EST
  • Pagination for PHP
            <div id='pagination'>
                <span class='curr'>Page <?php echo $page; ?> of <?php echo $totalPages; ?></span>
                <?php
                $range = 3;
                // build previous page
                if ($page > 1)
                    echo "<span><a href='{$_SERVER['PHP_SELF']}?page=".($page-1)."'>Previous</a></span> ";
                // build range pages
                $stop = ($page + $range) + 1;
                for ($x=($page-$range); $x<$stop; $x++) 
                {
                    // if it's a valid page number...
                    if (($x > 0) && ($x <= $totalPages)) 
                    {
                        if ($x == $page)
                            echo "<span class='curr'>$x</span> ";
                        else
                            echo "<span><a href='{$_SERVER['PHP_SELF']}?page=$x'>$x</a></span> ";
                    }
                }
                // build last page
                if ($stop <= $totalPages) 
                    echo "... <span><a href='{$_SERVER['PHP_SELF']}?page=$totalPages'>$totalPages</a></span> ";
                // build next page
                if ($page != $totalPages)
                    echo "<span><a href='{$_SERVER['PHP_SELF']}?page=".($page+1)."'>Next</a></span>";
                ?>
            </div>
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Jan 02, 2010 at 2:12 p.m. EST
  • PHP Recursive Sort
    <?php
    
    // Notice the & symbol in the args and in the FOREACH.
    // Omitting the & in the FOREACH will not save the sorts!
    
        private function recursSort(&$tree)
        {
            asort($tree);
            
            foreach ($tree as &$t)
            {
                if ($t['children'] != '')
                {
                    $t['children'] = $this->recursSort($t['children']);
                }
            }
            
            return $tree;
        }
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Oct 28, 2009 at 2:56 p.m. EDT
  • Correct way to do Pagination in Zend
    <?
    //In other words, instead of this:
    
        $select= $this->db->select()->from( 'runz_miles', 'EMPL_NO')->where('empl_no = ?', 31713);
        $this->view->result = $this->db->fetchAll($sql);
        $paginator = Zend_Paginator::factory($this->view->result);
    
    //Do this:
    
        $select= $this->db->select()->from( 'runz_miles', 'EMPL_NO')->where('empl_no = ?', 31713);
        $paginator = Zend_Paginator::factory($select);
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Oct 13, 2009 at 9:59 a.m. EDT
  • Command line PHP with args
    <?php
    
    // processing php arguments 
    if (count($argv) < 2)
    	die("Error 1: arg1 should be filename");
    
    $filename = $argv[1];
    
    // allow only letters and dot 
    if (preg_match("/[^A-Za-z0-9.]/", $filename) || preg_match("/[.]{2,}/", $filename))
    	die('Error 2');
    
    // Example usage:  
    // /usr/bin/php -f <phpscript.php> file.txt
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Oct 11, 2009 at 9:32 a.m. EDT
  • Regex: Date format
    <?
    // Date must match format: mm/dd/yyyy
    if (!preg_match('/^\d{2}\/\d{2}\/\d{4}$/', $due_date))
      echo "Error !";
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Sep 15, 2009 at 3:38 p.m. EDT
  • Read CSV File
    <?
    $fp = fopen($csv_file,'r');
    
    while (($data = fgetcsv($fp, 1000, ",")) !== false) 
    {
    	// make sure we all 6 columns and it isn't the header
    	if (count($data) == 6 && $data[0] != 'Name')
    	{
    		// extract the data
    		$name = $data[0];
            }
    }
    fclose($fp);
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Sep 12, 2009 at 12:23 p.m. EDT
  • XML (Simple XML) parse
    <?
    ==============================
    XML stuff (simple parse)
    
    // simple xml way
    
    // set the XML file name as a PHP string
    $myGroceryList = "output.xml" ; 
    // load the XML file 
    $xml = @simplexml_load_file($myGroceryList) or die ("no file loaded");
    // or load the string
    $xml = @simplexml_load_string($blah_string) or die ("error loading");
    
    echo var_export($xml);
    
    foreach ($xml->foodGroup as $foodGroup) {
      echo "<h2>Food group name is " . $foodGroup->groupName . "</h2>" ;
      foreach ($foodGroup->item as $foodItem) {
          echo "<br /> Item: " . $foodItem->name ;
          echo "<br /> Quantity: " . $foodItem->howMuch ;
          echo "<br />" ;
      }
      echo "<br />" ;
    }
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Sep 10, 2009 at 8:33 p.m. EDT
  • XML (SAX Parse) for PHP
    <?
    ==============================
    XML stuff (sax parse)
    
    // parse xml and store into array
    $xml_parser = xml_parser_create();
    xml_set_element_handler($xml_parser, "startTag", "endTag");
    xml_set_character_data_handler($xml_parser, "xmlEngine");
    $fp = fopen('xml/'.$xmlFile, "r") or die("Could not open file");
    
    // rbanh comment: apparently, for large sets of data the sax xml parser
    // tend to truncate data. So I'll have to create my own buffer to 
    // increase the size.
    $bufferCounter = 0;
    $bufferStorage = '';
    while( $data = fread( $fp, 8192 ) )
    {	
    	if ($bufferCounter % 2)
    	{
    		$bufferStorage .= $data;
    		xml_parse( $xml_parser, $bufferStorage );
    		$bufferStorage = '';
    	} else
    		$bufferStorage = $data;
    	
    	$bufferCounter++;
    }
    // make sure there isn't any more in the buffer
    if ($bufferStorage != '')
    	xml_parse( $xml_parser, $bufferStorage );
    xml_parser_free($xml_parser);
    fclose($fp); 
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Sep 10, 2009 at 8:31 p.m. EDT
  • php error checking
    <?
    
    // ==============
    // error checking
    // ==============
    if ($xmlFile === false) die('1');
    
    // max char length
    if (isset($xmlFile{201})) die('File name too long');
    
    // regex check for chars, numbers, periods, dash, and underscores only
    // also make sure there isn't 2 or more period next to each other.
    if (preg_match("/[^A-Za-z0-9_.\-]/", $xmlFile) || 
        preg_match("/[.]{2,}/", $xmlFile))
          die('2');
    
    // check if extension is xml
    if (!preg_match("/[.]xml$/", $xmlFile)) 
        die('3');
    
    // check if file exist
    if (!file_exists($_SERVER['DOCUMENT_ROOT']."/blah/$xmlFile"))
        die('File does not exist.');
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Sep 10, 2009 at 8:30 p.m. EDT
  • php strip out html tags
    <?
    // =======================
    // helper function to strip out html tags
    // =======================
    public function html2txt($document)
    {
      $search = array('#<script[^>]*?>.*?</script>#si',  // Strip out js
    		   '#<[\/\!]*?[^<>]*?>#si',          // Strip out HTML tags
    		   '#<style[^>]*?>.*?</style>#siU',  // Strip style tags properly
    		   '#<![\s\S]*?--[ \t\n\r]*>#'       // Strip multi-line comments including CDATA
    	);
    	
       $text = preg_replace($search, '', $document);
       return $text;
    }
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Sep 10, 2009 at 8:11 p.m. EDT
  • regex - remove 2 or more whitespaces
    <?
    // remove multiple whitespaces
    $line1 = preg_replace("\s{2,}", " ", $line1);
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Sep 10, 2009 at 8:08 p.m. EDT
  • regex to return only first set
    <?
    // extract just the first element
    $firstset = ereg_replace("^(.*) abc", "\\1", $data); 
    
    // note: \\1 is the same as javascript's $1
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Sep 10, 2009 at 8:08 p.m. EDT
  • regex - replace invalid chars with underscore
    <?
    // replace invalid chars with underscore (good for filename)
    $name = preg_replace("/[^a-z0-9-]/", "_" ,$name);
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Sep 10, 2009 at 8:05 p.m. EDT
  • PHP Regex example of greedy and lazy
    <?
    
    $x = '<p id="test">p1</p> <p id="test">p2</p>';
    
    // greedy
    if (preg_match('#<p id="test">(.+)</p>#', $x))
        echo "greedy";
    
    // lazy 1
    if (preg_match('#<p id="test">(.+?)</p>#', $x))
        echo "lazy 1";
    
    // lazy 2
    if (preg_match('#<p id="test">([^<]+)</p>#', $x))
        echo "lazy 2";
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Sep 10, 2009 at 7:51 p.m. EDT
Sign up to create your own snipts, or login.