PHP: Array 2 JSON

Author: Adrià Cidre  |  Category: PHP

Genial función en PHP que transforma un array PHP en una salida tipo Json. Genial para PHP4 que no integraba esta funcionalidad de serie.


function array2json($arr) {
  if(function_exists('json_encode')) return json_encode($arr); //Lastest versions of PHP already has this functionality.
  $parts = array();
  $is_list = false; 

  //Find out if the given array is a numerical array
  $keys = array_keys($arr);
  $max_length = count($arr)-1;
  if(($keys[0] == 0) and ($keys[$max_length] == $max_length)) {//See if the first key is 0 and last key is length - 1
      $is_list = true;
      for($i=0; $i$value) {
      if(is_array($value)) { //Custom handling for arrays
          if($is_list) $parts[] = array2json($value); /* :RECURSION: */
          else $parts[] = '"' . $key . '":' . array2json($value); /* :RECURSION: */
      } else {
          $str = '';
          if(!$is_list) $str = '"' . $key . '":'; 

          //Custom handling for multiple data types
          if(is_numeric($value)) $str .= $value; //Numbers
          elseif($value === false) $str .= 'false'; //The booleans
          elseif($value === true) $str .= 'true';
          else $str .= '"' . addslashes($value) . '"'; //All other things
          // :TODO: Is there any more datatype we should be in the lookout for? (Object?) 

          $parts[] = $str;
      }
  }
  $json = implode(',',$parts); 

  if($is_list) return '[' . $json . ']';//Return numerical JSON
  return '{' . $json . '}';//Return associative JSON
}

TextMate: Sintaxis en ficheros ctp (CakePHP)

Author: Adrià Cidre  |  Category: CakePHP, TextMate

Para resaltar la sintaxis de los ficheros ctp, es tan sencillo como seguir los siguientes pasos.

Abre la consola y escribe

$ cd ~/Library/Application\ Support/TextMate/Bundles

A continuación

$ svn co http://macromates.com/svn/Bundles/trunk/Review/Bundles/PHP\ Cake.tmbundle

Ahora solo tienes que abrir los ficheros con extensión ctp y listo

PHP: Aspectratio, redimension de imagenes al vuelo.

Author: Adrià Cidre  |  Category: PHP

Buenas a todos,

En uno de los comentarios de uno de los posts de este blog, Víctor nos comentaba como podía redimensionar imágenes con PHP, hace años que utilizo esta técnica, y personalmente la llamo aspectratio.

El script en cuestión recibe tres parámetros:

p: el path donde está la imagen original, puede ser una url o un fichero en el servidor.
w: el ancho máximo que queremos que tenga la imagen final
h: el alto máximo que queremos que tenga la imagen final.


$datos = getimagesize($nombre);
if($datos[2]==1){$img = @imagecreatefromgif($nombre);}
if($datos[2]==2){$img = @imagecreatefromjpeg($nombre);}
if($datos[2]==3){$img = @imagecreatefrompng($nombre);} 

$ratio = ($datos[0] / $anchura);
$altura = ($datos[1] / $ratio); 

if($altura>$hmax){$anchura2 = $hmax*$anchura/$altura;$altura=$hmax;$anchura=$anchura2;}
$thumb = imagecreatetruecolor($anchura,$altura); 

if($datos[2]==1)
	{
	$trnprt_indx  = imagecolortransparent($img);
	$trnprt_color = imagecolorsforindex($img, $trnprt_indx);
	$trnprt_indx  = imagecolorallocate($thumb, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);

	imagefill($thumb, 0, 0, $trnprt_indx);
	imagecolortransparent($thumb, $trnprt_indx);
	}
elseif ($datos[2]==3)
	{
	imagealphablending($thumb, false);
	$color = imagecolorallocatealpha($thumb, 0, 0, 0, 127);
	imagefill($thumb, 0, 0, $color);
	imagesavealpha($thumb, true);
	}

imagecopyresampled($thumb, $img, 0, 0, 0, 0, $anchura, $altura, $datos[0], $datos[1]); 

if($datos[2] == 1){header("Content-type: image/gif"); imagegif($thumb);}
if($datos[2] == 2){header("Content-type: image/jpeg"); imagejpeg($thumb);}
if($datos[2] == 3){header("Content-type: image/png"); imagepng($thumb); } 

imagedestroy($thumb); 

Este script escupe por pantalla la imagen, con lo que podemos llamarla para que nos convierta imágenes al vuelo.

Esta es una opción muy válida si no tienes acceso a instalar librerías en tu hosting. Si puedes hacerlo, deberías echarle un ojo a ImageMagick que ofrece unos resultados infinitamente mejores que no la librería GD (más extendida en hostings).

PHP – BBentities

Author: Adrià Cidre  |  Category: MiniCodes, PHP, Programación

Con esta función podemos convertir todas las entidades BB de una cadena en sus correspondientes HTML.
Se basa en expresiones regulares para descodificar una cadena codificada con el leguaje BBCode.

function bbentities($string)
{
    $string = strip_tags($string);

    $patterns = array(
        "bold" => "#\[b\](.*?)\[/b\]#is",
        "italics" => "#\[i\](.*?)\[/i\]#is",
        "underline" => "#\[u\](.*?)\[/u\]#is",
        "link_title" => "#\[url=(.*?)](.*?)\[/url\]#i",
        "link_basic" => "#\[url](.*?)\[/url\]#i",
        "color" => "#\[color=(.*?)\](.*?)\[/color\]#is"
    );

    $replacements = array(
        "bold" => "$1",
        "italics" => "$1",
        "underline" => "$1",
        "link_title" => "$2",
        "link_basic" => "$1",
        "color" => "$2"
    );

    return preg_replace($patterns, $replacements, $string);
}

Espero que os sirva :-)

PHP – recorrer parámetros POST

Author: Adrià Cidre  |  Category: MiniCodes

Bucle en PHP que recorre todos los elementos enviados por post, dándonos acceso tanto al nombre de las variables, como al valor de las mismas


while (list($key, $value) = each($_POST)){
	echo "\n$key => $value 
"; }

PHP – Traducción Automatica

Author: Adrià Cidre  |  Category: PHP

Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 7680 bytes) in /home/oridokic/public_html/blog/wp-includes/formatting.php(211) : runtime-created function on line 1