Imagine the situation where you need to read a list of configuration permissions, these permissions are inside of an XML file called permisos.xml in a valid directory of your server. In this short article we will see how to read an XML file, parse it and create an array with all entries of this file. There are several ways to do this, but we will use the compatible option with Joomla 2.5 API, why? well, because Joomla 2.5 is the stable and recommended version -currently- of this CMS (Content Management System). So, please let me show you how to complete this task.
Next is a valid XML file:
<?xml version="1.0" encoding="utf-8"?> <permisos> <grupo id="8" nombre="Administrators"> <modulo nombre="COM_ADMIN_ORDER_MOD" visible="true"> <menu nombre="COM_ORDER_S" visible="true"></menu> <menu nombre="COM_REPORT" visible="true"></menu> <menu nombre="COM_USER_S" visible="true"></menu> <menu nombre="COM_SHOPPERGROUP_S" visible="true"></menu> <menu nombre="COM_COUPON_S" visible="true"></menu> </modulo> </grupo> <grupo id="11" nombre="Team Members"> <modulo nombre="COM_ADMIN_ORDER_MOD" visible="false"> <menu nombre="COM_ORDER_S" visible="false"></menu> <menu nombre="COM_REPORT" visible="true"></menu> <menu nombre="COM_USER_S" visible="false"></menu> <menu nombre="COM_SHOPPERGROUP_S" visible="false"></menu> <menu nombre="COM_COUPON_S" visible="false"></menu> </modulo> </grupo> </permisos>
Now, with this simple code we can read all this file using Joomla 2.5 classes and methods, in particular we will use the static method getXML() from JFactory.
$usuario =& JFactory::getUser(); $grupos_usuario = $usuario->groups; $permisos = array(); // Reading file $xmlfile = JURI::base().'/some_path/permisos.xml'; $xml = JFactory::getXML($xmlfile,true); foreach($xml->children() as $grupo): $id_grupo_xml = $grupo->getAttribute("id"); foreach($grupo->children() as $modulo): // Permissions by module foreach($grupos_usuario as $id_grupo): if(in_array($id_grupo_xml, $grupos_usuario)) $permisos[$id_grupo][$modulo->getAttribute("nombre")] = $modulo->getAttribute("visible"); endforeach; // Permissions for each menu entry in every one of the modules foreach($modulo->children() as $menu): foreach($grupos_usuario as $id_grupo): if(in_array($id_grupo_xml, $grupos_usuario)) $permisos[$id_grupo][$menu->getAttribute("nombre")] = $menu->getAttribute("visible"); endforeach; endforeach; endforeach;// all modules endforeach; // all groups echo "<pre>"; print_r($permisos); echo "</pre>";
After reading content of the XML file we will get an output like this:
Array ( [8] => Array ( [COM_ADMIN_ORDER_MOD] => true [COM_ORDER_S] => true [COM_REPORT] => true [COM_USER_S] => true [COM_SHOPPERGROUP_S] => true [COM_COUPON_S] => true ) )
As you can see, it is really easy to read XML files, if you have some comments about this, please let me know.
Be happy with your code!
—
MariMon Oyarzabal liked this on Facebook.
Lidia Guerrero Calderón liked this on Facebook.