【问题标题】:Read a namespaced attribute from a SimpleXmlElement (imported from XMLReader)从 SimpleXmlElement 读取命名空间属性(从 XMLReader 导入)
【发布时间】:2011-08-25 11:58:26
【问题描述】:

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

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

如果我只是对每个“产品”节点使用 $reader->read() 函数,我可以将值检索为 $reader->value,但如果我 expand() 节点并使用 $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');

                } 

        }
    }

可能我错过了一些东西......任何建议都会非常受欢迎!

谢谢。

【问题讨论】:

标签: php simplexml domdocument xmlreader


【解决方案1】:

名称中带有冒号的属性具有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;

顺便说一句,如果您想将此数据导入数据库,您也可以尝试直接这样做:

【讨论】:

  • thanx,这个答案真的很有帮助!
猜你喜欢
  • 2013-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-30
  • 1970-01-01
  • 1970-01-01
  • 2012-03-25
  • 1970-01-01
相关资源
最近更新 更多