Go to the navigation

elblogg

Posts Tagged ‘php’

PHP frustration

Most of the code I’ve written in my life so far has been PHP, as long as I include all the small testing of different stuff just to see if it could be done.

PHP is quick to prototype stuff in, because you quickly get something you can poke around with, there’s little boilerplate code. However, specially when I’m just hacking together something in a hurry, theres one thing that’s really, really frustrating. Specially when I deal with SimpleXMLElements.

In Python you can do this:

?View Code PYTHON
firstbar=element.getElementsByTagName("bar")[0]

to get the first bar element inside “element”, in Java, i can do pretty much the same, and even in javascript you could do this, but in PHP, you always have to assign the result of getElementsByTagName() to a variable before accessing it’s index.

<?
print $element->xpath("//bar")[0]; // FAILS
$bars=$element->xpath("//bar");
print $bars[0]; //WORKS
?>

Now of course, this is not the only thing that frustrates me with PHP, but this was the thing biting me yesterday.

EDIT:
I realize that the best way to do this is using the current() function in PHP:

<?
print $element->xpath("//bar")[0]; // FAILS
print current($element->xpath("//bar")); // WORKS
?>

Flickr shortcode (and some nice HDR photos)

I like using creative commons photos from flickr as illustrations on my blog, however, I find it tedious to add all the metadata to satisfy the BY directive in the creative commons license in a consistent manner. Then it’s really nice that flickr has an API where I can automatically fetch that information. I use the shortcode feature of wordpress, so I can use

[flickr url="http://www.flickr.com/photos/stuckincustoms/4099398743/in/photostream/"]

to include an image like below:

Crossing the Bridge into Old Lyon by Trey Ratcliff ( Stuck in Customs on flickr)

or

[flickr pid="4097758830"]

to insert the image below:

or to get another size version i can use

[flickr pid="4088949046" version="Small"]

, like below:

The River Runs Through the Andes by Trey Ratcliff ( Stuck in Customs on flickr)
Tokyo Road by Trey Ratcliff ( Stuck in Customs on flickr)

Here’s the code, notice that you need to get an API key from the flickr api site:

<?
/**
  * This piece of code is created by Bård Aase <elzapp@gmail.com>, 
  *  and is licensed under the GPL.
  *  Contact me if you need another license. 
  */
function sc_flickr($atts){
    /**
     * This function gathers information about a flickr image, and complies with the
     * shortcode API in Wordpress.
     * @param $atts array of options
     *   Options:    pid: picture id
     *               version: Small, Medium or Large (default:Medium)
     *               class: class to apped to the <div class="image "> so you can style it
     *               url: You can use an URL instead of a picture id, the pid will be 
     *                     extracted
     */
    $FLICKR_APIKEY="INSERT YOUR API KEY HERE"
    extract(shortcode_atts(array(
    "pid" => $atts[0],
    "version"=>"Medium", //setting default value
    "class"=>"centered", //setting default value
    "url"=>""
    ), $atts));
    if($url != ""){
       $e=explode("/",$url);
       $pid=$e[5];
    }
    /* broken into several lines to look better on the blog */
    $sizes_url="http://api.flickr.com/services/rest/?method=flickr.photos.getSizes";
    $sizes_xml=file_get_contents("{$sizes_url}&api_key={$FLICKR_APIKEY}&photo_id=$pid");
    $info_url="http://api.flickr.com/services/rest/?method=flickr.photos.getInfo";
    $info_xml=file_get_contents("{$info_url}&api_key={$FLICKR_APIKEY}&photo_id=$pid");
    $c=new SimpleXMLElement($info_xml);
    $sizes=new SimpleXMLElement($sizes_xml);
 
    $size=$version;
    $un=$c->xpath("//owner/@username");
    $rn=$c->xpath("//owner/@realname");
    $t=$c->xpath("//title");
    $u=$c->xpath("//url");
    $image=$sizes->xpath("//size[@label='$size']/@source");
    $width=$sizes->xpath("//size[@label='$size']/@width");
    $height=$sizes->xpath("//size[@label='$size']/@height");
    $fontsize="A";
    if($height[0] > 300 & $width[0] > 500){
        $fontsize="C";
    }elseif($height[0] > 200 & $width[0] > 300){
        $fontsize="B";
    }
    $r=<<<EOT
<div class="image imageclass{$fontsize} {$class}" style="width:{$width[0]}px">
<img src="{$image[0]}" width="{$width[0]}" height="{$height[0]}"><div class="caption">
<span class="title"><a href="{$u[0]}">{$t[0]}</a></span> 
    <span class="author">by {$rn[0]} ( 
    <a href="http://flickr.com/photos/{$un[0]}">{$un[0]}</a> on flickr)</span>
</div>
</div>
EOT;
    return $r;
}
?>

Put that in a file in your theme directory, and call the file “flickr.php”, then put the following into the functions.php-file in the same folder:

require_once("flickr.php");
add_shortcode('flickr','sc_flickr');

Note that this generates the HTML only, the visual style is added to your blog's css, here's the CSS I've used in this example:

 
.image { position:relative; }
.caption {
  position:absolute;
  bottom:0;
  left:0;
  right:0;
  padding:5px;
  background:transparent url(tr75b.png) repeat scroll left top;
  color:#FFF;
  font-family:"Trebuchet MS";
}
.image:hover .caption {
  background:#000;
}
.caption a {
  color:#CFC;
}
.image img {
  display:block;
}
.imageclassA { font-size:10px;}
.imageclassB { font-size:14px;}
.imageclassC { font-size:18px; }
.image.centered {
margin:auto;
}
.image.floatleft {
margin:5px;float:left;
}
.image.floatright {
margin:5px;float:right;
}

the image referenced in the stylesheet is available from here

Great news in the software world

During the last week there has been a couple of great releases in the software I use every day.


First out was Python 3.1. It was released June 27th and features

  • An ordered dictionary type
  • Various optimizations to the int type
  • New unittest features including test skipping and new assert methods.
  • A much faster io module
  • Tile support for Tkinter
  • A pure Python reference implementation of the import statement
  • New syntax for nested with statements


Next out was Mozilla Firefox 3.5, which was released earlier today (June 30th), most noteworty items from that release is the @font-face css-attribute, that allows web-designers to bundle custom fonts with their website designs, and use custom fonts in their design.  I have used that feature to change the header of my blog, you would se a grudge font if you use the new Firefox or Safari. They have also released a new javascript-engine, which they claim to be a lot faster than the old one. Also, support for the <video>-tag has been added.


Then last, but not least, the long awaited PHP 5.3.0 has been released, which provides namespaces and closures for PHP.

Merging two lists

Lets say you have two lists, one of them containing the values [1,2,3] and the other one containing the values [4,5,6], and you want to combine these two lists into one list, like this one: [1,2,3,4,5,6].

Let’s see how this can be done in different (high level) programming (or scripting or templating) languages.

Java

Java has multiple list implementations, lets start with the most basic one, the builtin array.

int[] A = {1,2,3};
int[] B = {4,5,6};
int[] C = new int[A.length + B.length];
int counter=0;
for(int e : A){
  C[counter]=e;
  counter++;
}
for(int e : B){
  C[counter]=e;
  counter++;
}

or with an ArrayList:

/*Dropped importing the correct classes, 
and constructing the ArrayLists A and B, since thats not the focus here...*/
List<Integer> C = new ArrayList();
C.addAll(A);
C.addAll(B);

PHP

So, how is the same done in PHP?

$A=array(1,2,3);
$B=array(4,5,6);
$C=array_merge($A,$B);

Python

And at last, how does the Pythonistas do this?

?View Code PYTHON
A=[1,2,3]
B=[4,5,6]
C=A + B

Note: the rubyists use the same approach.

Merkelapper

De observante der ute (og som ikke bare leser bloggen min fra rss-leseren sin) kan ha oppdaget at merkelappene på bloggpostene har fått et nytt utseende.

Det begynte egentlig med at jeg så på en post jeg hadde skrevet og tenkte “Hm, de taggene der ser ikke ut som om de egentlig hører hjemme der”. Videre tenkte jeg, hva skal jeg gjøre for å få dem mer inn i det visuelle uttrykket på bloggen. Det hadde vært fint med noen bilder, men da må jeg vedlikeholde en haug med bilder for alle taggene. Det har jeg forsøkt før, da bare for kategoriene, og det er nesten ti ganger så mange tagger som kategoriene.

Hva om jeg kunne lage en bakgrunn som fikk merkelappene til å se mer ut som merkelapper? Vel.. min assosiasjon til merkelapper i denne sammenhengen er slike brune lapper som brukes på postsekker. Jeg kunne alltids lage en bakgrunn som så slik ut, men jeg syntes det ville være rart om de bare gikk rett horisontalt.

Her kommer vi til en av de tingene som jeg har savnet i CSS. En mulighet til å rotere objekter.

Velvel. vi kan jo alltids generere bilder på serveren, og bruke det… Og det var akkurat det jeg endte opp med også. Ikke bare får jeg da generert merkelappene slik jeg vil ha dem, men jeg kan velge den fonten jeg vil ha også, selv om webfonts ikke er støttet i nettleserene enda.

Resultatet er merkelappene nedenfor, og php-koden som genererer dem finner du her
Og her er det jeg brukte for å putte det inn i wordpress-temaet

Upgraded to wordpress 2.6.5

with a

# svn sw http://svn.automattic.com/wordpress/tags/2.6.5
U    wp-includes/post.php
U    wp-includes/version.php
U    wp-includes/feed.php
U    xmlrpc.php
U    wp-admin/users.php

I just upgraded multiple blogs running WordPress 2.6.3 (hups… seems like i missed one release).
Here’s the release announcement

edit
Nope, the 2.6.5 release is the first release after 2.6.3…

Note that we are skipping version 2.6.4 and jumping from 2.6.3 to 2.6.5 to avoid confusion with a fake 2.6.4 release that made the rounds. There is not and never will be a version 2.6.4.
from the release note…

Upgrading WordPress to 2.5

According to Stuart Herbert, if you use the advanced TinyMCE editor instead of the builtin wysiwyg editor, disable it before upgrading. Its not compatible with 2.5 (yet).

On the other hand, always disable all plugins before upgrading, and enable them one by one afterwards.

And, Bjørge, I will get back to what I did to make WP-upgrading easy soon.

Bloggurat Twingly BlogRank Blogglisten