/ Gists / PHP

Gists - PHP

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;

}

?>

On gists

Toyota (php reference)

1oldies PHP

store.php #

<?php

class Store
{
  function Store($db)
  {
    $this->db = &$db;
    $this->lang = 'cz';
    $this->itemsOff();
    
    $this->cars = array(
                       "toyota" => 1,
                       "lexus" => 2,
                       "scion" => 3,
                       "daihatsu" => 4
                     );
    
  }
 
 
 // definuje IDcka kategorii
 function itemsOff()
 {
  // bazar 49, 63, 77, 91
  // demo 48, 62, 76, 90
   $this->itemOff = array( 
                           "bazar" => array (49, 63, 77, 91),
                           "demo" => array (48, 62, 76, 90)
                         );
 }
 
 
 /**
  * Prida polozku do pole
  */   
 function addItemToArray(& $array, $key, $value)
 {
   if ($key != 0)
     $array[$key] = $value;
   else
     $array[] = $value;  
 }
 
 // vypise sklad podle typu auta a kategorie
 // sekce demo ma navic Najeto
 // sekce bazar navic Najeto + Rok vyroby
 function dump($car, $cat)
 {
   $sql  = " SELECT * FROM sklad WHERE auto = ".$this->cars[$car];
   $sql .= " AND kategorie = $cat ";
   $sql .= " AND aktivni = 'ano' ";
   $sql .= " ORDER BY ID DESC ";
   
   $sql = $this->db->query($sql);
   
   if ($this->db->numRows($sql))
   {
   
   
   echo "<table style='border: 1px solid black; margin: 0 auto; width: 850px; border-collapse: collapse;'>";
   $this->thNames = array(1 => "Foto", 2 => "Model", 3=> "Barva", 4 => "Motor");
   
   // zapinam polozku pro demo
    if (in_array($_GET["pid"], $this->itemOff["demo"]))
     { 
       $this->addItemToArray($this->thNames, 5, "Najeto");
     }
    // zapinam polozku pro bazar  
    if (in_array($_GET["pid"], $this->itemOff["bazar"]))
     { 
       $this->addItemToArray($this->thNames, 5, "Rok výroby");
       $this->addItemToArray($this->thNames, 6, "Najeto");
     }  
     
     // Cena
    $this->addItemToArray($this->thNames, 0,  "Cena");
   
   
   // cena je az na konci
   
   echo "<tr>";
   foreach ($this->thNames as $v)
    {
     echo "<th style='text-align: left; padding: 5px;'>".$v."</th>";
    }
   echo "</tr>";
   while ($r = $this->db->fetch($sql))
    {
    
    $this->tdNames = array(
                         1 => "<a href='./images/sklad/foto_popup_{$r->ID}_thumb.jpg' rel=\"lightbox\"><img src='./images/sklad/foto_thumb_{$r->ID}_thumb.jpg' /></a>", 
                         2 => $r->model,
                         3 => $r->barva,
                         4 => $r->motor
                          );


      // zapinam polozku pro demo
    if (in_array($_GET["pid"], $this->itemOff["demo"]))
     { 
       $this->addItemToArray($this->tdNames, 5, $r->najeto);
     }
    // zapinam polozku pro bazar  
    if (in_array($_GET["pid"], $this->itemOff["bazar"]))
     { 
       $this->addItemToArray($this->tdNames, 5, $r->rok_vyroby);
       $this->addItemToArray($this->tdNames, 6, number_format($r->najeto, 0, "", ".") . " Km");
     }  
     
     // Cena
     //number_format($number, 2, ',', ' ');
    $this->addItemToArray($this->tdNames, 0,  number_format($r->cena, 0, "", ".") . " Kč");

      echo "<tr>";

          foreach ($this->tdNames as $v)
          {
            echo "<td style='text-align: left; border-bottom: 1px dotted black; padding: 5px'>".$v."</td>";
          }
          echo "</tr>";
      
    } 
    echo "</table><br />";
  }
 }
 
 
  
} // class
?>

On gists

Find in array - recursive

PHP

find-in-array.php #

<?php


$arr = [
    'name' => 'Php Master',
    'subject' => 'Php',
    'type' => 'Articles',
    'items' => [
        'one' => 'Iteration',
        'two' => 'Recursion',
        'methods' => [
            'factorial' => 'Recursion',
            'fibonacci' => 'Recursion',
        ],
    ],
    'parent' => 'Sitepoint',
];



echo find_in_arr('one', $arr, 'devka');


print_r($arr);


function find_in_arr($key,  &$arr, $replace) {
    foreach ($arr as $k => &$v) {
        if ($k == $key) {
			$arr[$k] = $replace;
            return $v;
        }
        if (is_array($v)) {
            $result = find_in_arr($key, $v, $replace);
            if ($result != false) {
                return $result;
            }
        }
    }	
    return false;
}

On gists

PHP Factory

PHP

factory.php #

<?php 
 

$arr = [
    'company' => 'AMI',
    'employeeCount' => 25,
    'years' => 12,
    'bankInfo' => [
        'account' => 'xxxx',
        'money' => '2 billions'
    ]
];


echo F::create()->getResource($arr)->formatToXml();

class F
{
    private $resource;

    public static function create()
    {
        return new self;
    }

    public function getResource($resource)
    {
        $this->resource = $resource;
        return $this;
    }

    public function formatToJson()
    {
        return json_encode($this->resource);
    }

    public function formatToArray()
    {
        return $this->resource;
    }

    public function formatToXml()
    {
        $xml = new SimpleXMLElement('<root/>');
        array_walk_recursive($this->resource, array ($xml, 'addChild'));
        return $xml->asXML();
    }


}

On gists

Foreach vs array_reduce

PHP

gistfile1.aw #

<?php

$arr = array(
	array('a', '1'),
	array('b', '2'),
);


// klasicky
$out = array();
foreach ($arr as $v) {
	$out[$v[0]] = $v[1];
}

// funkcionalne
$out2 = array_reduce($arr, function($out2, $v) {
	$out2[$v[0]] = $v[1];
	return $out2;
});

echo ($out === $out2) . "\n";
print_r($out);
print_r($out2);

/* vystup:

1
Array
(
    [a] => 1
    [b] => 2
)
Array
(
    [a] => 1
    [b] => 2
)

*/

On gists

Zyla simple parser

PHP

parser.php #

<?php

$x = file_get_contents($file);

$final = preg_match("~<tr[^>]*>(.+)</tr>~si", $x, $match);

$lastTr = strpos($match[0], '</tr>');
$match[0] = substr($match[0], $lastTr + 8,  strlen($match[0]));


file_put_contents("frag.txt", $match[0]);

$f = fopen("frag.txt", "r");

$cols = array("kolo", "datum", "cas", "domaci", "hoste", "skore", "strelci_karty");

//$in_td = false;
$rows = array();

while (!feof($f))
{
   $r = fgets($f);
   # preskocit prazdne radky
   if ( trim($r) != '' )
   {
      if (strpos($r, '<tr') !== false)
      {
        // $in_td=true;
         $rows = array();
      }
      else
      {
         if (strpos($r, '</tr') !== false)
         {
            //$in_td = false;
            #zpracuju $rows

            if (count($rows) == 8)
            {
               #mam v prvni bunce kolo
               $kolo = array_shift($rows);
            }
            zapis_insert($kolo, $rows);
            //print_r($rows);

         }
         else
         {
            if (strpos($r, '<td') !== false)
            {
               $t = preg_replace('/<[^>]*>/', '', trim($r));
               $rows[] = $t;
            }
         }
      }
   }
}

On gists

Curl - PHP auth

PHP

curl-php-auth.php #

<?php
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
		curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
		$output = curl_exec($ch);
		$info = curl_getinfo($ch);
		curl_close($ch);

On gists

PHP Auth

PHP

php-auth.php #

<?php

if (empty($_SERVER['PHP_AUTH_USER']) ||
     $_SERVER['PHP_AUTH_USER'] != "login" ||
     $_SERVER['PHP_AUTH_PW'] != "pass") {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Zde nemáte přístup bez jména a hesla';
    exit;
}

On gists

Gists API

PHP

gistApi.php #

<?php

class GistEdit {

	private $data;
	
	private static $_instance = NULL ;
	
	public static function init () {
		if (self::$_instance === NULL) {
            self::$_instance = new self;
        }
		self::$_instance->data = array();
        return self::$_instance;
	}
	
	public function edit ($file, $newContent = NULL, $newFileName = NULL) {
		
		if ($newContent !== NULL) {
			$this->data[$file]['content'] = $newContent ;
		}
		if ($newFileName !== NULL) {
			$this->data[$file]['filename'] = $newFileName ;
		}
		return $this;
	}
	
	public function deleteFile ($file) {
		$this->data[$file] = NULL ;
		return $this;
	}
	
	public function newFile ($file, $content){
		$this->data[$file]['content'] = $content;
		return $this;
	}
	
	public function get () {
		return $this->data;
	}

}

class gistAPI {
	
	private $url = "https://api.github.com" ;
	
	private $user = "github" ;
	
	public $ch ;
	
	private $response ;
	
	public $loginInfo ;
	
	
	function __construct($id = NULL, $pass = NULL) {
		if($id === NULL || $pass === NULL){
			$loginInfo = NULL;
		} else {
			$loginInfo = array('username' => $id,
							   'password' => $pass);
		}
		$this->loginInfo = $loginInfo;
		$this->chReset();
	}
	
	public function listGists ($type = "public", $user = NULL) {
	
		switch ($type) {
			case "public":
				curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/public");
				break;
			case "user":
				curl_setopt($this->ch, CURLOPT_URL, $this->url . "/users/" . ($user === NULL ? $this->user:$user) ."/gists");
				break;
			case "starred":
				curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/starred");
				break;
		}
		return $this->returnCode();
	
	}
	
	public function getGist ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/".$gistId);
		return $this->returnCode();
	
	}
	
	public function createGist ($files, $description = "", $public = false) {
	
		$filesArray = array();
		foreach ($files as $fileName => $content)
			$filesArray[$fileName]['content'] = $content;
		$postArray = array(
					"files"		  => $filesArray,
					"description" => $description,
					"public"	  => $public
					);
		$jsonArray = json_encode($postArray);
		
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists");
		curl_setopt($this->ch, CURLOPT_POST, 1);
		curl_setopt($this->ch, CURLOPT_POSTFIELDS, $jsonArray);
		return $this->returnCode();
	
	}
	
	public function editGist ($gistId, $files = NULL, $description = NULL) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId);
		curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
		if ($files === NULL && $description !== NULL) {
			$jsonArray = json_encode(array("description" => $description));
		} elseif ($description === NULL && $files !== NULL) {
			$jsonArray = json_encode(array("files" => $files));
		} elseif ($description !== NULL && $files !== NULL) {
			$jsonArray = json_encode(array("description" => $description, "files" => $files));
		} else {
			$this->chReset();
			return 0;
		}
		curl_setopt($this->ch, CURLOPT_POSTFIELDS, $jsonArray);
		return $this->returnCode();
	
	}
	
	public function gistCommits ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/" . $gistId . "/commits");
		return $this->returnCode();
	
	}
	
	public function starGist ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/star");
		curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'PUT');
		return $this->returnCode();
	
	}
	
	public function unstarGist ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/star");
		curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
		return $this->returnCode();
	
	}
	
	public function checkStarGist ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/star");
		return $this->returnCode();
	
	}
	
	public function forkGist ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/forks");
		curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'POST');
		return $this->returnCode();
	
	}
	
	public function listForkGist ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/forks");
		return $this->returnCode();
	
	}
	
	public function deleteGist ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId);
		curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
		return $this->returnCode();
	
	}
	
	public function gistComments ($gistId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/".$gistId."/comments");
		return $this->returnCode();
	
	}
	
	public function getComment ($gistId, $commentId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/comments/". $commentId);
		return $this->returnCode();
	
	}
	
	public function createComment ($gistId, $comment){
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/comments");
		curl_setopt($this->ch, CURLOPT_POST, 1);
		$jsonArray = json_encode(array("body" => $comment));
		curl_setopt($this->ch, CURLOPT_POSTFIELDS, $jsonArray);
		return $this->returnCode();
	
	}
	
	public function editComment ($gistId, $commentId, $comment) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/comments/". $commentId);
		curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
		$jsonArray = json_encode(array("body" => $comment));
		curl_setopt($this->ch, CURLOPT_POSTFIELDS, $jsonArray);
		return $this->returnCode();
	
	}
	
	public function deleteComment ($gistId, $commentId) {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/gists/". $gistId ."/comments/". $commentId);
		curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
		return $this->returnCode();
	
	}
	
	public function getLimits() {
	
		curl_setopt($this->ch, CURLOPT_URL, $this->url . "/rate_limit");
		return $this->returnCode();
	}
	
	private function parseHeader ($header_text) {
		
		$headers = array();
		foreach (explode("\r\n", $header_text) as $i => $line){
			if (strlen($line) > 1 && $i != 0){
				list ($key, $value) = explode(': ', $line);
				$headers[$key] = $value;
			} else if ($i == 0){
				$headers['http_code'] = $line;
			}
		}
		return $headers;
	}
	
	private function returnCode () {
	
		$this->response = curl_exec($this->ch);
		$header_size = curl_getinfo($this->ch, CURLINFO_HEADER_SIZE);
		$header = substr($this->response, 0, $header_size);
		$body = substr($this->response, $header_size);
		$return = array("header" => $this->parseHeader($header),
					 "body"	  => json_decode($body, true),
					 "raw"    => $this->response);
		$this->chReset();
		return $return;
	}
	
	public function chReset () {
	
		$this->ch = curl_init();
		curl_setopt($this->ch, CURLOPT_HEADER,         true);
		curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($this->ch, CURLOPT_TIMEOUT,        30);
		curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
		if ($this->loginInfo !== NULL){
			$this->user = $this->loginInfo['username'];
			curl_setopt($this->ch, CURLOPT_USERAGENT, $this->loginInfo['username']);
			curl_setopt($this->ch, CURLOPT_USERPWD, $this->loginInfo['username'].":".$this->loginInfo['password']);
		} else {
			curl_setopt($this->ch, CURLOPT_USERAGENT, "gistAPI v1.0");
		}
		unset($this->response);
	
	}
	
	function __destruct() {
		curl_close($this->ch);
	}

}
?>