Reputation: 1
I've inherited some php that parses an xml file to populate a page full of unordered lists and am wondering if there is a way to consolidate the php functions to make them more efficient.
There are 25 or so functions like the following:
function oaAccounting(){
// load SimpleXML
$term = new SimpleXMLElement('training_list.xml', null, true);
echo <<<EOF
<ul>
EOF;
foreach($term as $term)
{
if(preg_match("/accounting/i", $term->keyword)){
echo <<<EOF
<li>{$term->name}</li>
EOF;
}
}
echo '</ul>';
}
each one scans the xml file for the term/keyword it's searching for and adds the term as a list element to an unordered list specific to that function. The next function does the same thing but for a different term/keyword and adds it to a separate unordered list.
is there a way to combine all this to prevent having to do the foreach and if 25 times in a row?
Thanks!
Upvotes: 0
Views: 69
Reputation: 174967
Abstract your function.
Pass the file and the search terms as arguments to the function, and work with that.
Something like:
function parse_xml_file($file, $terms)
Then use pass $file
and $terms
when calling the function.
For more information, see Teh big bad manual.
Upvotes: 1
Reputation: 219814
This revised function takes one parameter, the word to look for, and then uses it in the preg_match() function. So to use it all you need to do is call it with the term you're searching for. This should replace all of the hard coded functions.
function searchXML($search){
// load SimpleXML
$terms = new SimpleXMLElement('training_list.xml', null, true);
echo <<<EOF
<ul>
EOF;
foreach($terms as $term)
{
if(preg_match("/$search/i", $term->keyword)){
echo <<<EOF
<li>{$term->name}</li>
EOF;
}}
echo '</ul>';
}
Upvotes: 0