SimpleXML - Replace Tags with Our Data (Page 2 of 5 )
Let’s play tag:
As you can see the XML document contains three main elements, header, body, and footer. With in each of those we have the basic three column page layout, and a few proprietary tags such as <!title> and <!logo>. These are going to be the elements that we’re going to replace with our own non-template data. So first things first, we need to figure out how to replace the tags with our data. I created the following function to do so.
function replace($load,$string,$mask='<!-tag->'){
if(!is_array($load)){
return $string;
}else{
if(!strpos($load,'-tag-')) $mask='<!-tag->';
$masks=explode('-tag-',$mask);
$tags=array_keys($load);
foreach($tags as $tag){
$newtags[]=$masks[0].$tag.$masks[1];
}
$loads=array_values($load);
return str_replace($newtags,$loads,$string);
}
}
Before we go any farther, lets take a look at this function so you know exactly what it does.
First we define the function and all the parameters it will accept:
- $load is the array of tags we’re going to replace, the array should be set up like this array(‘tagname’=>”data to place where the tag is”)
- $string is the variable that holds the XML string that we’ll later get from simpleXML
- $mask is an optional variable that you can use incase you want to use a different tag style, such as <*tag> function replace($load,$string,$mask='<!-tag->'){
Then we make sure that $load is an array so that we don’t get any nasty unexpected errors. If it’s not an array the function will just return the XML string without processing it
if(!is_array($load)){
return $string;
}
If $load is an array, we first make sure that there isn’t a tag in the $load named “-tag-“(1). Then we explode the $mask tag by “-tag-“ so that we have an array that has the opening and closing brackets for each tag, “<!” and “>”(2). Now you might say “why all this stuff about the tags being explode to simply get the ‘<!’ and ’>’.” The reason behind that is so that you can change the tag style to something else like <*-tag-> if you want.
(1) if(!strpos($load,'-tag-')) $mask='<!-tag->';
(2) $masks=explode('-tag-',$mask);
Now we’re about to use a built-in PHP function that isn’t used too often but is very useful, array_keys(). array_keys() returns the keys of the input array as the values of the output array consider the following.
$array1 = array('key1'=>"value1",'key2'=>"value2");
$array2 = array_keys($array1);
print_r($array2);
This will output:
Array
(
[0] => key1
[1] => key2
)
Pretty cool and useful isn’t it.
Next: Build List of Tags >>
More XML Articles
More By James Murray