脚本宝典收集整理的这篇文章主要介绍了php – Zend:如何使用Zend_Config_Xml管理多个元素具有相同名称的XML数据?,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
<?xml version="1.0" encoding="UTF-8" ?> <root> <stylesheets> <stylesheet>example1.css</stylesheet> <stylesheet>example2.css</stylesheet> </stylesheets> </root>
这是代码:
$data = new Zend_Config_Xml('./path/to/xml_file.xml','stylesheets'); $stylesheets = $data->stylesheet->toArray();
我想要做的是使用foreach循环遍历$stylesheet数组,提取文件名,然后将样式表附加到headLink().这工作正常…但是,当< stylesheet>的数量时,我遇到了问题.元素小于2.因此,例如,如果我们@L_304_13@< stylesheet> example2.css< / stylesheet>从XML文件中,我遇到致命错误:在非对象上调用成员函数toArray().你会如何应对这种情况?
更新1 – 替代SimpleXML解决方案:
就个人而言,我使用SimpleXML解决了这个问题,因为Zend导致我太多的白发.即使没有< stylesheet>这也会有用.元素.不幸的是,我并不觉得它非常“光滑”,并希望有一个Zend解决方案.
// 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); }
更新2 – 笨重的Zend解决方案:
根据反馈,这个解决方案适用于0到多个数字样式表元素…它不是很漂亮.我希望有一个松散耦合的设计,标准化的东西,你可以互换使用,但同时也很容易实现.
// 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); } } }
以上是脚本宝典为你收集整理的php – Zend:如何使用Zend_Config_Xml管理多个元素具有相同名称的XML数据?全部内容,希望文章能够帮你解决php – Zend:如何使用Zend_Config_Xml管理多个元素具有相同名称的XML数据?所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。