How to write PHP with CSS Syntax

on Tuesday, 02 August 2011.

I've recently designed a template system, and wanted to make it as easy as possible for the designers to enter values into PHP functions. So I wrote a little function to allow a CSS style string to be converted into an array.

Regular PHP Method

//The line of code the designer has to edit
echo createPosition('header', '100px', '200px');

function createPosition($name, $height, $width)
{
  return  '<div id="' . $name . '" style="height:' . $height . ';width:' . $width . ';">' . $name . '</div>';
}

CSS Style PHP

//The line of code the designer has to edit
echo createPosition('name:header; width:100px; height:200px');

function attrStringToArray($attr_string)
{
  $attr = array();
  foreach(explode(';', $attr_string) AS $attr_temp) {
    if (strlen(trim($attr_temp)) > 0) {
      list($name, $value) = explode(':', $attr_temp);
      $attr[trim($name)] = trim($value);
    }
  }
  return $attr;
}

function createPosition($attr_string)
{
  $attributes = attrStringToArray($attr_string);
  return  '<div id="' . $attributes['name'] . '" style="height:' . $attributes['height'] . ';width:' . $attributes['width'] . ';">' . $attributes['name'] .'</div>';
}

So you can see that the line of code the designer has to edit is a lot easier to understand with the CSS style PHP. The attributes can also be in any order. This is just one scenario and can be used in many.

blog comments powered by Disqus