可以通过XML重写这种迭代吗?

时间:2016-08-04 07:56:21

标签: php optimization

我有以下代码来遍历xml文件。

$nodelist = $xml->getElementsByTagName('cv');
foreach ($nodelist as $node) {
   $naam = $node->getElementsByTagName('naam');
   $naamid = $naam->item(0)->nodeValue;
}

有没有办法让价值在一行?

$nodelist = $xml->getElementsByTagName('cv');
foreach ($nodelist as $node) {
   $naamid = <a one line to get the nodevalue of naam out of the  xml>;
}

1 个答案:

答案 0 :(得分:1)

你甚至可以在一行上完成整个程序,使用Generators你可以创建一个单行函数来获取naam元素的所有实例:

// Returns a generator which gets all elements with 'naam'
function getNaamElements()
{
    foreach ($xml->getElementsByTagName('cv') as $node) 
    {
        yield $node->getElementsByTagName('naam')->item(0)->nodeValue;
    }
}

// To get an array:
$array = iterator_to_array(getNaamElements());

// To loop over all 'naam' elements in another loop, use the generator instead
foreach (getNaamElements() as $naam)
{
    // Do stuff with $naam
}