note 29636 added to function.var-export
| From: | khowe at perfnet dot ca | Date: | Wed, 19 Feb 2003 19:12:56 +0000 |
| Subject: | note 29636 added to function.var-export | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-44221@lists.php.net to get a copy of this message | ||
The function posted above by metze (10-Jan-2003 04:17) is great, but contains the following flaws:
1. Array keys are not quoted.
If the value is the same as any PHP keyword (ex: function) it will cause problems.
Example:
$arr = array('function'=>'value');
var_export($arr);
The produced output will be:
array(function=>'value')
Which will fail when evaluated, because "function" is a PHP keyword.
2. String values are not properly quoted.
In metze's version the value is surrounded by single quotes, but single quotes *inside* the
value are not escaped.
If the value contains single quotes, an error will occur.
Example:
$str = "My 'single quoted' value.";
var_export($str);
The produced output will be:
'My 'single' quoted value'
Which will fail since the single quotes were not properly escaped.
Solution:
For both keys and values, escape any single quotes, then surround with single quotes.
Example: $str = "'".str_replace("'", "\'",
$str)."'";
Modified function;
if (! function_exists('var_export'))
{
function var_export_rec ($a, $return, $ext_tab_sep, $inside_array)
{
if ($inside_array != false)
{
$tab_sep = '';
$sep = ",\n";
}
else
{
$tab_sep = $ext_tab_sep;
$sep = "\n";
}
$result = '';
switch ( gettype($a) )
{
case 'array':
reset($a);
$result = $tab_sep."array(\n";
while (list($k, $v) = each($a)) {
$result .= $ext_tab_sep."\t"."'".str_replace("'",
"\'", $k)."'".' =>
'.var_export_rec($v,$return,$ext_tab_sep."\t",true);
}
$result .= $ext_tab_sep.')'.$sep;
break;
case 'string':
$result = $tab_sep."'".str_replace("'", "\'",
$a)."'".$sep;
break;
case 'boolean':
$result = ($a) ? $tab_sep.'true'.$sep : $tab_sep.'false'.$sep;
break;
default:
$result = $tab_sep.$a.$sep;
break;
}
if ($return != false) {
return $result;
} else {
echo $result;
}
}
function var_export ($a, $r=false) {
return var_export_rec($a, $r, '', false);
}
--
http://www.php.net/manual/en/function.var-export.php
http://master.php.net/manage/user-notes.php?action=edit+29636
http://master.php.net/manage/user-notes.php?action=delete+29636
http://master.php.net/manage/user-notes.php?action=reject+29636