note 53755 rejected from function.str-replace by mazzanet

From: Date: Sun, 12 Jun 2005 04:07:18 +0000
Subject: note 53755 rejected from function.str-replace by mazzanet
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-90282@lists.php.net to get a copy of this message
Note Submitter: mxgxw at navegante dot com dot sv ---- Estaba buscando alguna forma de realizar sustituciones rápidas en un archivo de plantillas, intenté usar un sistema de sustitución usando output buffer, sin embargo me vi en el inconvenente que con los archivos XML las etiquetas <? y ?> en algunos servidores se evaluaban como php, impidiendome usar cualquier archivo de plantillas. Por ello diseñe un codigo utilizando str_replace que busca las ocurrencias de variables en un archivo de plantillas y las reemplaza por el valor especificado. La definicion de las variables se hace así: <?php $vars["{label1}"] = "Test1"; $vars["{label2}"] = "Test2"; ?> Y la evaluación haciendo uso de str_replace, de la siguiente manera: <?php function processTemplate($file,$vals) { if(is_file($file)) { $buffer = file_get_contents($file); foreach($vals as $var=>$val) { $buffer = str_replace($var,$val,$buffer); } return $buffer; } else return NULL; } ?> El archivo html usado: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Untitled Document</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body> {label1} {label2} </body> </html> Y la respectiva salida haciendo uso de: echo procesarPlantilla("test.htm",$vars); Salida: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Untitled Document</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body> Test1 Test2 </body> </html>

« previous php.notes (#90282) next »