/ Gists / PHP

Gists - PHP

On gists

PHP CLI colors & getopts commands

PHP CLI

cli.php #

<?php

// https://www.supercoders.in/2019/07/php-command-line-php-parsing-program_16.html
// https://misc.flogisoft.com/bash/tip_colors_and_formatting
// https://joshtronic.com/2013/09/02/how-to-use-colors-in-command-line-output/

$longopts  = array(
    "required:",     // Required value
    "optional::",    // Optional value
    "option",        // No value
    "opt",           // No value
);

$options = getopt("", $longopts);

echo "\e[0;34;41mMerry Christmas!\e[0m\n";
echo "kunda";
echo "\033[31m some colored text \033[0m some white text \n";
echo  "Normal \e[5mBlink \n";
echo "Normal \e[1mBold \n";
echo "Default \e[33mYellow \n";


On gists

Microtime - rychlost měření php kódu

PHP

mereni.php #

<?php


function starttime() {
$r = explode( ' ', microtime() );
$r = $r[1] + $r[0];
return $r;
}

function endtime($starttime) {
$r = explode( ' ', microtime() );
$r = $r[1] + $r[0];
$r = round($r - $starttime,4);
return '<strong>Execution Time</strong>: '.$r.' seconds<br />';
}



$start = starttime();

$list = [1,2,3,4,5];

for ($i=0 ; $i< 1e5; $i++) {
    
	if (count($list))
	{
	}
}

echo endtime($start);



$start = starttime();

$list = [1,2,3,4,5];

for ($i=0 ; $i< 1e6; $i++) {
    
	if (!isset($x))
	{
		$x = [];
	}
}

echo endtime($start);

On gists

Distance between 2 points

PHP

distance.php #

<?php


echo get_distance(50.0598058, 14.3255396, 51.0769658, 13.6325016, 'Km');


function get_distance($latitude1, $longitude1, $latitude2, $longitude2, $unit = 'Mi') { 
    $theta = $longitude1 - $longitude2; 
    $distance = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + 
                (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * 
                cos(deg2rad($theta))); 
    $distance = acos($distance); 
    $distance = rad2deg($distance); 
    $distance = $distance * 60 * 1.1515; 
    switch($unit) { 
        case 'Mi': 
            break; 
        case 'Km' : 
            $distance = $distance * 1.609344; 
    } 
    return (round($distance,2)); 
}

On gists

Remove accents

PHP

remove.php #

<?php

function removeAccents($str)
{
    static $map = [
        // single letters
        'à' => 'a',
        'á' => 'a',
        'â' => 'a',
        'ã' => 'a',
        'ä' => 'a',
        'ą' => 'a',
        'å' => 'a',
        'ā' => 'a',
        'ă' => 'a',
        'ǎ' => 'a',
        'ǻ' => 'a',
        'À' => 'A',
        'Á' => 'A',
        'Â' => 'A',
        'Ã' => 'A',
        'Ä' => 'A',
        'Ą' => 'A',
        'Å' => 'A',
        'Ā' => 'A',
        'Ă' => 'A',
        'Ǎ' => 'A',
        'Ǻ' => 'A',


        'ç' => 'c',
        'ć' => 'c',
        'ĉ' => 'c',
        'ċ' => 'c',
        'č' => 'c',
        'Ç' => 'C',
        'Ć' => 'C',
        'Ĉ' => 'C',
        'Ċ' => 'C',
        'Č' => 'C',

        'ď' => 'd',
        'đ' => 'd',
        'Ð' => 'D',
        'Ď' => 'D',
        'Đ' => 'D',


        'è' => 'e',
        'é' => 'e',
        'ê' => 'e',
        'ë' => 'e',
        'ę' => 'e',
        'ē' => 'e',
        'ĕ' => 'e',
        'ė' => 'e',
        'ě' => 'e',
        'È' => 'E',
        'É' => 'E',
        'Ê' => 'E',
        'Ë' => 'E',
        'Ę' => 'E',
        'Ē' => 'E',
        'Ĕ' => 'E',
        'Ė' => 'E',
        'Ě' => 'E',

        'ƒ' => 'f',


        'ĝ' => 'g',
        'ğ' => 'g',
        'ġ' => 'g',
        'ģ' => 'g',
        'Ĝ' => 'G',
        'Ğ' => 'G',
        'Ġ' => 'G',
        'Ģ' => 'G',


        'ĥ' => 'h',
        'ħ' => 'h',
        'Ĥ' => 'H',
        'Ħ' => 'H',

        'ì' => 'i',
        'í' => 'i',
        'î' => 'i',
        'ï' => 'i',
        'ĩ' => 'i',
        'ī' => 'i',
        'ĭ' => 'i',
        'į' => 'i',
        'ſ' => 'i',
        'ǐ' => 'i',
        'Ì' => 'I',
        'Í' => 'I',
        'Î' => 'I',
        'Ï' => 'I',
        'Ĩ' => 'I',
        'Ī' => 'I',
        'Ĭ' => 'I',
        'Į' => 'I',
        'İ' => 'I',
        'Ǐ' => 'I',

        'ĵ' => 'j',
        'Ĵ' => 'J',

        'ķ' => 'k',
        'Ķ' => 'K',


        'ł' => 'l',
        'ĺ' => 'l',
        'ļ' => 'l',
        'ľ' => 'l',
        'ŀ' => 'l',
        'Ł' => 'L',
        'Ĺ' => 'L',
        'Ļ' => 'L',
        'Ľ' => 'L',
        'Ŀ' => 'L',


        'ñ' => 'n',
        'ń' => 'n',
        'ņ' => 'n',
        'ň' => 'n',
        'ʼn' => 'n',
        'Ñ' => 'N',
        'Ń' => 'N',
        'Ņ' => 'N',
        'Ň' => 'N',

        'ò' => 'o',
        'ó' => 'o',
        'ô' => 'o',
        'õ' => 'o',
        'ö' => 'o',
        'ð' => 'o',
        'ø' => 'o',
        'ō' => 'o',
        'ŏ' => 'o',
        'ő' => 'o',
        'ơ' => 'o',
        'ǒ' => 'o',
        'ǿ' => 'o',
        'Ò' => 'O',
        'Ó' => 'O',
        'Ô' => 'O',
        'Õ' => 'O',
        'Ö' => 'O',
        'Ø' => 'O',
        'Ō' => 'O',
        'Ŏ' => 'O',
        'Ő' => 'O',
        'Ơ' => 'O',
        'Ǒ' => 'O',
        'Ǿ' => 'O',


        'ŕ' => 'r',
        'ŗ' => 'r',
        'ř' => 'r',
        'Ŕ' => 'R',
        'Ŗ' => 'R',
        'Ř' => 'R',


        'ś' => 's',
        'š' => 's',
        'ŝ' => 's',
        'ş' => 's',
        'Ś' => 'S',
        'Š' => 'S',
        'Ŝ' => 'S',
        'Ş' => 'S',

        'ţ' => 't',
        'ť' => 't',
        'ŧ' => 't',
        'Ţ' => 'T',
        'Ť' => 'T',
        'Ŧ' => 'T',


        'ù' => 'u',
        'ú' => 'u',
        'û' => 'u',
        'ü' => 'u',
        'ũ' => 'u',
        'ū' => 'u',
        'ŭ' => 'u',
        'ů' => 'u',
        'ű' => 'u',
        'ų' => 'u',
        'ư' => 'u',
        'ǔ' => 'u',
        'ǖ' => 'u',
        'ǘ' => 'u',
        'ǚ' => 'u',
        'ǜ' => 'u',
        'Ù' => 'U',
        'Ú' => 'U',
        'Û' => 'U',
        'Ü' => 'U',
        'Ũ' => 'U',
        'Ū' => 'U',
        'Ŭ' => 'U',
        'Ů' => 'U',
        'Ű' => 'U',
        'Ų' => 'U',
        'Ư' => 'U',
        'Ǔ' => 'U',
        'Ǖ' => 'U',
        'Ǘ' => 'U',
        'Ǚ' => 'U',
        'Ǜ' => 'U',


        'ŵ' => 'w',
        'Ŵ' => 'W',

        'ý' => 'y',
        'ÿ' => 'y',
        'ŷ' => 'y',
        'Ý' => 'Y',
        'Ÿ' => 'Y',
        'Ŷ' => 'Y',

        'ż' => 'z',
        'ź' => 'z',
        'ž' => 'z',
        'Ż' => 'Z',
        'Ź' => 'Z',
        'Ž' => 'Z',


        // accentuated ligatures
        'Ǽ' => 'A',
        'ǽ' => 'a',
    ];
    return strtr($str, $map);
}

On gists

Iteration and Recursive Iteration Examples Code

PHP

iteration-and-recursive-iteratio #

<?php
/*
* Iteration and Recursive Iteration Examples Code
*
* @link http://stackoverflow.com/questions/12077177/how-does-recursiveiteratoriterator-works-in-php
* @author hakre <http://hakre.wordpress.com>
*/

### To have these examples to work, a directory with subdirectories is needed,
### I named mine "tree":

$path = 'tree';


/**
 * Example 1: DirectoryIterator
 */
$dir = new DirectoryIterator($path);

echo "[$path]\n";
foreach ($dir as $file) {
    echo " ├ $file\n";
}


/**
 * Example 2: IteratorIterator
 */
$files = new IteratorIterator($dir);

echo "[$path]\n";
foreach ($files as $file) {
    echo " ├ $file\n";
}


/**
 * Example 3: RecursiveDirectoryIterator
 */
$dir = new RecursiveDirectoryIterator($path);

echo "[$path]\n";
foreach ($dir as $file) {
    echo " ├ $file\n";
}


/**
 * Example 4: RecursiveIteratorIterator
 */
$files = new RecursiveIteratorIterator($dir);

echo "[$path]\n";
foreach ($files as $file) {
    echo " ├ $file\n";
}


/**
 * Example 5: Meta-Information
 */
echo "[$path]\n";
foreach ($files as $file) {
    $indent = str_repeat('   ', $files->getDepth());
    echo $indent, " ├ $file\n";
}


/**
 * Example 6: Recursion Mode
 */
$dir   = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);

echo "[$path]\n";
foreach ($files as $file) {
    $indent = str_repeat('   ', $files->getDepth());
    echo $indent, " ├ $file\n";
}


/**
 * Appendix: Nicely Formatted Directory Listings (as used in the answer)
 */
$unicodeTreePrefix = function(RecursiveTreeIterator $tree)
{
    $prefixParts = [
        RecursiveTreeIterator::PREFIX_LEFT         => ' ',
        RecursiveTreeIterator::PREFIX_MID_HAS_NEXT => '│ ',
        RecursiveTreeIterator::PREFIX_END_HAS_NEXT => '├ ',
        RecursiveTreeIterator::PREFIX_END_LAST     => '└ '
    ];
    foreach ($prefixParts as $part => $string) {
        $tree->setPrefixPart($part, $string);
    }
};

$dir  = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_FILENAME | RecursiveDirectoryIterator::SKIP_DOTS);
$tree = new RecursiveTreeIterator($dir);
$unicodeTreePrefix($tree);

### non-recursive and recursive listing
foreach ([0, -1] as $level) {
    $tree->setMaxDepth($level);
    echo "[$path]\n";
    foreach ($tree as $filename => $line) {
        echo $tree->getPrefix(), $filename, "\n";
    }
}


/**
 * Appendix: Do It Yourself: Make the `RecursiveTreeIterator` Work Line by Line.
 */
$dir   = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
$lines = new RecursiveTreeIterator($dir);
$unicodeTreePrefix($lines);
echo "[$path]\n", implode("\n", iterator_to_array($lines));

echo "

/// Solution Suggestion ///

";
@include('recursive-directory-iterator-solution.php');

$lines = new RecursiveTreeIterator(
    new DiyRecursiveDecorator($dir)
);
$unicodeTreePrefix($lines);
echo "[$path]\n", implode("\n", iterator_to_array($lines));

On gists

PHP - sleep, outputbuffer (fake loading)

PHP

sleep.php #

<?php

if (ob_get_level() == 0) ob_start();

for ($i = 0; $i<10; $i++){

        echo "<br> $i Line to show.";
        echo str_pad('',4096)."\n";   

        ob_flush();
        flush();
        sleep(1);
}

echo "<br> Done.";

ob_end_flush();

On gists

Csv to UTF-8

PHP

csv.php #

<?php

	$csv = file_get_contents(INDEX_DIR . '/../temp/slozky-csv.csv');
	$csv = iconv("windows-1250//TRANSLIT//IGNORE", 'utf-8', $csv);
	$csv = explode("\n", $csv);

On gists

Recursive array walk with replace

PHP

recursive.php #

<?php

	protected function parseQueryData(&$array, $data) 
	{
		array_walk_recursive($array, function(&$item, $key) use ($data) 
		{
			if(substr($item, 0, 1) == '%') 
			{
				$item = $data[substr($item, 1)];
			}
		});
	}

On gists

Parsing og tags

PHP PHP-PHPDOM

parser.php #

<?php 


function autoUTF($s)
{
    if (preg_match('#[\x80-\x{1FF}\x{2000}-\x{3FFF}]#u', $s)) // detect UTF-8
    {
        return $s;
    }
    elseif (preg_match('#[\x7F-\x9F\xBC]#', $s)) // detect WINDOWS-1250
    {
        return iconv('WINDOWS-1250', 'UTF-8', $s);
    }
    else // assume ISO-8859-2
    {
        return iconv('ISO-8859-2', 'UTF-8', $s);
    }
}
 

$url = 'https://navratdoreality.cz/uzdraveny-fotbalista-8853.html';

$html = file_get_contents($url);

libxml_use_internal_errors(true); // Yeah if you are so worried about using @ with warnings
$doc = new DomDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$query = '//*/meta[starts-with(@property, \'og:\')]';
$metas = $xpath->query($query);
$rmetas = array();
foreach ($metas as $meta) {
    $property = $meta->getAttribute('property');
    $content = $meta->getAttribute('content');
    $rmetas[$property] = html_entity_decode(autoUTF($content));
}
var_dump($rmetas);



// $pattern='/<\s*meta\s+property="og:([^"]+)"\s+content="([^"]*)/i';
// preg_match_all($pattern, $html, $out);
// var_dump(array_combine($out[1], $out[2]));

On gists

Array multisort

PHP

example1.php #

<?php


$hodnoty = array(
                
                "baku" => array(3, 4, 7),
                "kcko" => array(2, 5, 7),
                "guest" => array(1, 2, 2)
                );

$data = array();

foreach ($hodnoty as $pole => $k)
 {
   $counter = 0;
   foreach ($k as $i)
    {
      $counter++;
      //echo "$pole - $i [$counter] <br />";
      $data[$pole]["komentar" . $counter] = $i;
      if ($counter ==3 )
       {
        $data[$pole]["komentarCelkem"] = array_sum($hodnoty[$pole]);
       }
    }
 }


print_r($data);

$dataSort = valuesToColumns($data); 

 array_multisort(
                 
                 $dataSort["komentarCelkem"], SORT_NUMERIC, SORT_DESC,
                 $dataSort["komentar1"], SORT_NUMERIC, SORT_DESC,
                 $dataSort["komentar2"], SORT_NUMERIC, SORT_DESC,
                 $dataSort["komentar3"], SORT_NUMERIC, SORT_DESC
                 
                 );



print_r($dataSort);

$tab = "<table border=1>";
$tab .= "<tr><th>Nick</th> <th>Komentář Celkem</th> <th>Komentář 1</th> <th>Komentář 2</th> <th>Komentář 3</th> </tr>";

foreach ($dataSort["komentar1"] as $K => $V)
{
 
 $tab .= "<tr>";
 $tab .= "<td>$K</td>";
 $tab .= "<td>". $data[$K]["komentarCelkem"] ."</td>";
 $tab .= "<td>". $data[$K]["komentar1"] ."</td>";
 $tab .= "<td>". $data[$K]["komentar2"] ."</td>";
 $tab .= "<td>". $data[$K]["komentar3"] ."</td>";
 $tab .= "</tr>";
 
}
$tab .= "</table>";


echo $tab;




function valuesToColumns($array_to_sort)
{

   $sort_arr = array();
   foreach($array_to_sort AS $uniqid => $row)
   {
       foreach($row AS $key=>$value){
           $sort_arr[$key][$uniqid] = $value;
       }
   }
   
   return $sort_arr;

}

?>