如何从 XML 解析中排除某些记录


How can I exclude certain records from an XML parse?

我使用以下代码从XML文件中提取数据:

<?php
$url = 'http://www.inveroak.com/readerimages/livepanel/91221.xml';
$xml = simplexml_load_file($url);
$items = array();
$exclude = array('4419','4373');
$items = array_diff($items, $exclude);
foreach($xml as $Reader) { 
    $items[] = $Reader; 
}
usort ($items, function($a, $b) { 
    return strcmp($a->Status,$b->Status); 
});
foreach($items as $Reader) { 
    if($Reader->Status != 'Logged Off' && $Reader->Picture != 'None')
        {
        include '/extras/reader-single.php';
        }
}
?>

显示$exclude和$items的两行我已经添加在看到另一篇帖子后,从关于从 XML 中排除的 foreach 循环中排除值,但是当我加载页面时......指定了 PIN 的两条记录仍然显示。

这是排除从 XML 文件中提取某些记录的正确方法吗?

任何帮助将不胜感激!

编辑:输入的四位数字是在读取器>PIN中找到的PIN码经过思考,会不会是它没有在xml文件上的数字和Reader->PIN之间建立链接?

有一种更简单的方法来专门查询属性 - 或排除它们。

$url = 'http://www.inveroak.com/readerimages/livepanel/91221.xml';
$xml = simplexml_load_file($url);
$matches = $xml->xpath( "//Reader[Pin!=4419 and Pin!=4373]" );

这将为您提供整个结构,减去#4419和#4373两个项目。

正如我在评论中所说,获取每条记录的引脚,将其与排除数组进行比较,如果它是排除数组的一部分,则继续循环。喜欢这个:

$url = 'http://www.inveroak.com/readerimages/livepanel/91221.xml';
$xml = simplexml_load_file($url);
$items = array();
$exclude = array('4419','4373');
$items = array_diff($items, $exclude);
foreach($xml as $Reader) { 
    $items[] = $Reader; 
}
usort ($items, function($a, $b) { 
    return strcmp($a->Status,$b->Status); 
});
foreach($xml as $Reader) { 
    if($Reader->Status != 'Logged Off'
        && $Reader->Picture != 'None'
        // check if the Pin is in exclude array
        && !in_array($Reader->Pin, $exclude)
    ) { 
        include '/extras/reader-single.php';
    }   
}

或者,您可以使用array_filter()

$url = 'http://www.inveroak.com/readerimages/livepanel/91221.xml';
$xml = simplexml_load_file($url);
$items = array();
$exclude = array('4419','4373');
$items = array_diff($items, $exclude);
foreach($xml as $Reader) { 
    $items[] = $Reader; 
}
$items= array_filter($items, function($Reader) use ($exclude) {
    if($Reader->Status == 'Logged Off'
       || $Reader->Picture == 'None'
       || in_array($Reader->Pin, $exclude)
    ) { 
        return false;
    }   
    return true;
});
usort ($items, function($a, $b) {
    return strcmp($a->Status,$b->Status);
});
foreach($items as $Reader) {
    include '/extras/reader-single.php'; 
}

另一种方法是在第一个 foreach 循环中过滤掉它们:

foreach($xml as $Reader) {
    if (array_search($Reader->Pin, $exclude) === FALSE) {
         $items[] = $Reader;
    }
}

无论哪种情况,您都不需要:

$items = array_diff($items, $exclude);

array_diff() 返回第一个数组 ($items) 中第二个数组 ($exclude) 中不存在的值。 因为在你的情况下,第一个数组是一个空数组,它没有值,所以 array_diff() 也将始终返回一个空数组。

也许有人会提供XPath解决方案 - 这将是另一种方法。(编辑 - 啊,我看到@pp19dd提供了这个。