使用 PHP XMLReader 对 XML 树中的所有属性进行排序 [英] Sort through all attributes in XML tree with PHP XMLReader

查看:36
本文介绍了使用 PHP XMLReader 对 XML 树中的所有属性进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 PHP 代码可以将 XML 文件转换为 CSV 文件.在测试期间,我没有创建 CSV 文件,只是以 CSV 格式回显结果.

I have some PHP code to turn an XML file into a CSV file. During testing, I am not creating a CSV file, just echoing the results in a CSV format.

每当 XMLReader 遇到一个空元素时,它就会输出该元素的所有属性.

Whenever XMLReader reaches an empty element, it outputs all the attributes of the element.

1) 有没有办法输出属性名称及其值,即(是否有 $xml->AttributeName 与 $xml->value 一起使用)?

1) Is there a way to output the attribute name with it's values i.e. (is there an $xml->AttributeName that goes with the $xml->value)?

2) 有没有办法对整个树中的所有属性进行排序,而不仅仅是对空元素中的属性进行排序?

2) Is there a way to sort for all attributes in the entire tree and not just those in the empty element?

<?php 

ini_set('memory_limit','50M');

$x = file_get_contents('H8_data.xml');

$xml = new XMLReader(); 
$xml->open('H8_data.xml', null, 1<<19); 

$num = 1;
while ($xml->read() && $num <= 2000) {
    if($xml->isEmptyElement) {
        if($xml->hasAttributes)  {
            while($xml->moveToNextAttribute()) { 
                echo $xml->value, ', '; 
            }
        }
    echo '<br />';
    $num++;
    }
}

?>

推荐答案

$xml->name 返回节点的限定名称.因为属性是具有 XMLReader::ATTRIBUTE 类型的节点,在这种情况下 $xml->name 将返回当前属性的名称.下面是代码版本,它输出属性名称和值.

$xml->name returns the qualified name of the node. Because attributes are nodes with XMLReader::ATTRIBUTE type, $xml->name will return the name of current attribute in that case. Below is version of code, which outputs both attribute names and values.

<?php 

ini_set('memory_limit','50M');

$x = file_get_contents('H8_data.xml');

$xml = new XMLReader(); 
$xml->open('H8_data.xml', null, 1<<19); 

$num = 1;
while ($xml->read() && $num <= 2000) {
    if($xml->isEmptyElement) {
        if($xml->hasAttributes)  {
            while($xml->moveToNextAttribute()) { 
                echo $xml->name, ' = ', $xml->value, ', '; 
            }
        }
    echo '<br />';
    $num++;
    }
}
?>

这篇关于使用 PHP XMLReader 对 XML 树中的所有属性进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆