Zend: How to manage XML data when multiple elements have the same name using Zend_Config_Xml?

When trying to extract data from an XML file using Zend_Config_Xml , I am looking for a better way to process this data when multiple elements have the same name. Please take a look at the following example.

Here is the XML file:

 <?xml version="1.0" encoding="UTF-8" ?> <root> <stylesheets> <stylesheet>example1.css</stylesheet> <stylesheet>example2.css</stylesheet> </stylesheets> </root> 

Here is the code:

 $data = new Zend_Config_Xml('./path/to/xml_file.xml', 'stylesheets'); $stylesheets = $data->stylesheet->toArray(); 

What I would like to do is iterate over the $stylesheet array using the foreach loop, extracting the file name, and then add the stylesheets to headLink() . This works great ... however, I run into problems when the number of <stylesheet> elements is less than 2. So, for example, if we remove the <stylesheet>example2.css</stylesheet> from the XML file, I am in Fatal error: Call to a member function toArray() on a non-object . How would you handle this situation?

UPDATE 1 - Alternative SimpleXML Solution:

Personally, I solved this problem using SimpleXML, as Zend caused me too much gray hair. This will work even if there are no <stylesheet> elements. Unfortunately, I do not feel very β€œsmooth” and was hoping for a Zend solution.

 // define path to skin XML config file $path = './path/to/file'; if (file_exists($path)) { // load the config file via SimpleXML $xml = simplexml_load_file($path); $stylesheets = (array)$xml->stylesheets; // append each stylesheet foreach ($stylesheets as $stylesheet) { if (is_array($stylesheet)) { foreach ($stylesheet as $key => $value) { $this->setStylesheet('/path/to/css/' . $value); } } else { $this->setStylesheet('/path/to/css/' . $stylesheet); } } } // function to append stylesheets private function setStylesheet($path) { $this->view->headLink()->appendStylesheet($path); } 

UPDATE 2 - Zend Unlimited Solution:

Based on the feedback, this solution works from 0 to many stylesheet elements ... it's not very pretty. I was hoping for a loosely coupled design, something standardized, on which you could use interchangeable and at the same time simple tools for implementation at the same time.

 // load the skin config file $path = './path/to/file.xml'; if (file_exists($path)) { $data = new Zend_Config_Xml($path, 'stylesheets'); $stylesheets = $data->toArray(); // append each stylesheet if (array_key_exists('stylesheet', $stylesheets)) { foreach ((array)$stylesheets['stylesheet'] as $key => $value) { $this->view->headLink()->appendStylesheet( '/path/to/css/' . $value); } } } 
+4
source share
1 answer

Get an array and force an array if only 1 element:

 $data = new Zend_Config_Xml($c, 'stylesheets'); $data = $data->toArray(); var_dump((array) $data['stylesheet']); 
+2
source

Source: https://habr.com/ru/post/1399960/


All Articles