I use Coda for most of my coding needs on the Mac. I’m also a system’s guy so I use VI a lot to create simple scripts in perl, php and bash. When I’m creating a php script, on of the first things I do is add the opening and closing PHP tags. One of the drawbacks is that when you use the standard PHP closing tag ‘?>’ and then hit ‘enter’ in your keyboard while using Coda, it adds a blank line to the bottom of your file. In general this isn’t a problem but your RSS feeds or any XML feed for that matter will more than likely have a blank line before the XML header. This causes some browsers – Firefox in particular – to complain about XML syntax.
I needed to find all files that had a blank line at the end. I love one-liners so here’s one that does the trick:
echo ‘<?php foreach (glob(”**/*.php”) as $file){if (preg_match( “/\\?”.”>\\s\\s+\\Z/m”, file_get_contents($file))) echo(”$file\n”);} ?>’ | php
If you like ruby, here’s a much simpler line:
ruby -e ‘Dir.glob( “**/*.php” ) { |file| puts file if IO.read(file).match( /\?>\s{2,}\Z/m) }’
Categories: PHP
Tagged: one liner, xml
Here’s an interesting item I doubt many PHP developers know. There’s a performance hit to using strings with double quotes instead of single quotes. According to an article written about simple PHP Optimizations by the helpful folks at google you may actually be hurting yourself by using double quotes in strings that use variables. Most programmers use this convention because it’s simple to type and easy to read. Apparently, using this convention tells the PHP engine to parse the string, look for variables inside it and replace them. If you use single quotes and concatenation, you won’t have this overhead.
In my simple, unscientific tests, it looks like there’s a 30% difference in performance if us use double-quotes.
I used a for loop with a simple string that used the loops variable inside it and echo’ed the line 100,000 times. I ran this 50 times and took used microtime to compute how long it took for the loop to complete. I did this using all the different combinations they discuss in the article and I did this on a local linux box to make sure network latency wasn’t a factor.
I found that using the comma versus the period for concatenation didn’t affect performance in any significant way. Using double quotes took on average 30% longer to complete.
That’s a significant difference and something to keep in mind when writing code. I have no converted to using double quotes sparingly.
If you’re interested in the methodology, here’s the code that I’m sure someone will pick-apart.
<?php
$start=microtime();
$start=explode(” “,$start);
$start=$start[1]+$start[0];
for ($i=0; $i < 100000; $i++){
echo ‘this is a string with the variable: ‘,$i,chr(10);
}
$end=microtime();
$end=explode(” “,$end);
$end=$end[1]+$end[0];
printf(”generated in %f seconds\n”,$end-$start);
?>
Categories: PHP
Tagged: echo, optimizations