spl中有无类似c++ stl的 for_each函数,就是遍历iterator中所有元素,对每个元素执行一个function,尝试写了个 apply_to_all函数,貌似不对
$xmlstring = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<text>
<mod id = "usracc" name="User Accounts">
<item id="nusr" showname="New User"/>
<item id="ngroup" showname="New Group"/>
</mod>
<mod id = "dasboa" name = "Dashboard">
<item id="leftnewbtn" showname="New"/>
<item id="underLeftsavebtn1" showname="Save"/>
</mod>
<mod id = "popups" name="Popup Window Wrapper">
<item id="selectallbtn" showname="Select All"/>
<item id="cancelbtn" showname="Cancel"/>
</mod>
</text>XML;function apply_to_all(Traversable $it, $fn) {
foreach($it as $item) {
if(call_user_func_array($fn, array($item)) === false) {
break;
}
}
}try {
$it = new SimpleXMLIterator($xmlstring);
$mode = RecursiveIteratorIterator::SELF_FIRST; function cb($a) {//比如这里要打印每个节点的id属性
echo $a->getAttribute('id');// 这样写是不对的, $a->current()->getAttribute 也不对,应该咋写
debug($a);
} debug(apply_to_all(new RecursiveIteratorIterator($it, 1), 'cb'));
} catch(Exception $e) {
debug($e);
}
$xmlstring = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<text>
<mod id = "usracc" name="User Accounts">
<item id="nusr" showname="New User"/>
<item id="ngroup" showname="New Group"/>
</mod>
<mod id = "dasboa" name = "Dashboard">
<item id="leftnewbtn" showname="New"/>
<item id="underLeftsavebtn1" showname="Save"/>
</mod>
<mod id = "popups" name="Popup Window Wrapper">
<item id="selectallbtn" showname="Select All"/>
<item id="cancelbtn" showname="Cancel"/>
</mod>
</text>XML;function apply_to_all(Traversable $it, $fn) {
foreach($it as $item) {
if(call_user_func_array($fn, array($item)) === false) {
break;
}
}
}try {
$it = new SimpleXMLIterator($xmlstring);
$mode = RecursiveIteratorIterator::SELF_FIRST; function cb($a) {//比如这里要打印每个节点的id属性
echo $a->getAttribute('id');// 这样写是不对的, $a->current()->getAttribute 也不对,应该咋写
debug($a);
} debug(apply_to_all(new RecursiveIteratorIterator($it, 1), 'cb'));
} catch(Exception $e) {
debug($e);
}
比如
$it = new SimpleXMLIterator($xmlstring);
array_walk_recursive(new RecursiveIteratorIterator($it, 1), 'cb');
这样就不行,什么都没打印出
function apply_to_all(Traversable $it, $fn) {
foreach($it as $item) {
if(call_user_func_array($fn, array($item)) === false) {
break;
}
}
}
只是里面每一项都不是简单的DomElement,而是SimpleXMLElement,它有自己的一套方法