PHP和XML.使用PHP循环XML文件
发布时间:2020-12-13 21:42:50 所属栏目:PHP教程 来源:网络整理
导读:我现在正试图通过 PHP(遵循XML文件内容)来遍历这个XML文件(下面的实际XML文本). 我想要做的是以下内容: 获取所有文件夹元素名称 如果文件夹元素的yes为子文件夹属性,则向下移动一个级别并获取该文件夹元素的名称 如果没有移动到下一个文件夹元素 gallerylis
我现在正试图通过
PHP(遵循XML文件内容)来遍历这个XML文件(下面的实际XML文本).
我想要做的是以下内容: >获取所有文件夹元素名称 gallerylist.xml: <?xml version="1.0" encoding="ISO-8859-1"?> <gallerylisting exists="yes"> <folder subfolder="yes"> Events <folder subfolder="yes"> Beach_Clean_2010 <folder subfolder="no"> Onna_Village </folder> <folder subfolder="no"> Sunabe_Sea_Wall </folder> </folder> </folder> <folder subfolder="no"> Food_And_Drink </folder> <folder subfolder="no"> Inside </folder> <folder subfolder="no"> Location </folder> <folder subfolder="no"> NightLife </folder> </gallerylisting> gallerylisting.php <?php $xmlref = simplexml_load_file("gallerylisting.xml"); foreach($xmlref->children() as $child) { foreach($child->attributes() as $attr => $attrVal) { print $child; if($attrVal == "yes") { foreach($child->children() as $child) { echo $child; foreach($child->attributes() as $attr => $attrVal) { if($attrVal == "yes") { foreach($child->children() as $child) { echo $child; } } } } } } } 我…计数… 5个foreach循环深入到这个PHP脚本中我根本不喜欢它,如果我的文件夹有另一个子文件夹,我将不得不添加这个 $if(attrVal=="yes")...etc. 又好又好……不!无论如何,我可以避免这种情况.我是PHP的新手,特别是PHP和XML. 谢谢你的帮助. 解决方法
递归可能对你有益.
<?php function display_entities( $xml ) { foreach($xml->children() as $child) { foreach($child->attributes() as $attr => $attrVal) { print $child; if($attrVal == "yes") { display_entities( $child->children() ); } } } } $xmlref = simplexml_load_file("gallerylisting.xml"); display_entities($xmlref->children()); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |