php - 从 SimpleXmlElement 中读取命名空间属性(从 XMLReader 导入)

标签 php simplexml domdocument xmlreader

我正在尝试读取一个大的 xml 文件(大约 40 MB),并使用此数据更新我的应用程序的数据库。

我似乎在使用 XMLReader 和 simplexml_import_dom() 的运行时间/内存方面找到了一个很好的折衷方案,但我无法获得名称中带有冒号的属性的值...例如 <g:attr_name> .

如果我简单地为每个“产品”节点使用 $reader->read() 函数,我可以将值检索为 $reader->value,但是如果我展开 () 节点并使用 $doc->importNode 复制它此属性将被忽略。

    $reader = new XMLReader();
    $reader->open(__XML_FILE__);
    $doc = new DOMDocument;

    while ($reader->read()) {
        switch ($reader->nodeType) {
            case (XMLREADER::ELEMENT):
                if($reader->localName=="product"){
                   $node = simplexml_import_dom($doc->importNode($reader->expand(), true));
                   echo $node->attr_name."<br><br>";
                   $reader->next('product');

                } 

        }
    }

可能我错过了什么......任何建议都会非常有用!

谢谢。

最佳答案

名称中带有冒号的属性有一个 namespace .

冒号之前的部分是注册到某个命名空间(通常在根节点)的前缀。要访问 SimpleXmlElement 的命名空间属性,您必须将命名空间传递给 attributes()方法:

$attributes = $element->attributes('some-namespace'); // or
$attributes = $element->attributes('g', TRUE);        // and then
echo $attributes['name'];

这同样适用于节点的子元素。通过 childrens() 访问它们方法

$children = $element->children('some-namespace'); // or
$children = $element->children('g', TRUE);        // and then
echo $children->elementName;

旁注,如果你想将这些数据导入你的数据库,你也可以尝试直接这样做:

关于php - 从 SimpleXmlElement 中读取命名空间属性(从 XMLReader 导入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6001784/

相关文章:

php - SOAP 响应主体的 Simlpexml 和 registerxpathnamespace 问题

php - DomDoc/SimpleXML/XSLT : parsing to add auto-incrementing id attributes to each unique element child of an element

php - 尝试将 DOMDocument::loadHTMLFile 与生成的 url 一起使用

php - Codeigniter-在 window.print() 中每页限制 2 个图像

php - 无法更改 php session cookie 名称

PHP命名空间simplexml问题

php - DOMDocument::loadHTML():警告 - htmlParseEntityRef:实体中没有名称

php - 获取最后一个元素的 x 个数

php - 在 PHP 中使用准备好的语句插入/显示多个带有外键的 MySQL 表

php - 我可以隐藏 Controller 并查看名称 cake php 2 吗?