Why use PHP5?

Noticed an interesting thread on the PHP-general mailing list. The original thread was someone asking why should the world start adopting PHP5. Rasmus came back and answered the question with a list of benefits of making the change (using 5.1 not 5.0). Now I admit to not working with any of these, but many of them certainly look interesting enough for a second glance.

Rasmus’s list:

To me the main user-visible benefits of going to PHP 5 are (ignoring the OO changes for now):

1. Simplexml

eg. One-line RSS parser (of Flickr’s upload queue feed)

$url = ‘http://www.flickr.com/services/feeds/photos_public.gne‘;
foreach(simplexml_load_file($url)->entry as $it) echo $it->content;

2. Much improved DOM support

eg. various things you can do to a DOM

// First, load your XML document into a DOM
$dom = domdocument::load(‘test.xml’);

// Apply a stylesheet to the dom
$proc = new xsltProcessor;
echo $proc->transformToXML($dom);

// xpath query on the dom
$ctx = new domXPath($dom);
$result = $ctx->query(‘/top/child[@attr > 3]/foo/text()’);
foreach($result as $node) {
echo $node->nodeValue;

// pull it into simplexml and access it
$s = simplexml_import_dom($dom);
echo $s->child[0]->foo;

3. xmlreader/xmlwriter

eg. SAX document validation using xmlreader

$reader = new XMLReader();
$reader->setParserProperty(XMLReader::VALIDATE, true);
echo $reader->isValid();

4. PDO

eg. Prepare execute against MySQL with named parameters

$pdo = new PDO(‘mysql:dbname=testdb’);

$sql = ‘SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour'; $prep = $pdo->prepare($sql);
$prep->execute(array(‘:calories’ => 150, ‘:colour’ => ‘red’));
$red = $prep->fetchAll();


eg. Exposing your PHP code as a SOAP web service

function Add($x,$y) {
return $x+$y;
$server = new SoapServer(null,array(‘uri’=>“http://test-uri/”));

6. SPL

eg. Iterating over entries in a directory

$dir = new DirectoryIterator(‘.’);
foreach($dir as $ent) echo $ent;

7. Filter

eg. Define a default filter and use form input safely without cluttering
up your code with htmlspecialchars() calls everywhere and provide
easily auditable access to the unfiltered data

php.ini: filter.default = special_chars

echo $_POST[‘data’];
$raw = input_get(INPUT_POST,’data’, FILTER_UNSAFE_RAW);

8. Native Date/Time mechanism

Date/time functions now behave exactly the same way on every platform regardless of the differences in locales if you choose to use the native mechanism.

Beyond that the compiler produces smaller opcode arrays and the executor is faster. Not a directly visible thing, and this is still improving, but definitely a plus.

Note that for all of this I am referring to PHP 5.1.x, not 5.0.x.