如何在PHP中处理XML NODE

时间:2011-03-27 18:27:15

标签: php xml xml-parsing xmlnode

这是简单的代码。我只是想知道如何处理$reader->expand();

返回的节点
<?php
$reader = new XMLReader();
if (!$reader->open("data.xml"))
{
    die("Failed to open 'data.xml'");
}
while($reader->read())
{
    $node = $reader->expand();
    // just want to know how to process this node now?
}
$reader->close();
?>

1 个答案:

答案 0 :(得分:-1)

<?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<parent xmlns:dc="myNS"> 
<dc:child> <dc:a>A</dc:a> <dc:b>B</dc:b> </dc:child> 
<dc:child> <dc:a>c</dc:a> <dc:b>d</dc:b> </dc:child> 
<dc:child> <dc:a>e</dc:a> <dc:b>f</dc:b> </dc:child> 
<dc:child> <dc:a>g</dc:a> <dc:b>h</dc:b> </dc:child> 
</parent> 
XML;

$reader = new XMLReader();
$reader->xml($xml);
while($reader->read()) {
    switch($reader->nodeType) {
        case constant('XMLREADER::ELEMENT'):
            if ($reader->name == 'dc:child') {
                //insert into db
                var_dump($reader->readInnerXml());
            }
            break;
    }
}

$reader->close();

输出:

string(63) " <dc:a xmlns:dc="myNS">A</dc:a> <dc:b xmlns:dc="myNS">B</dc:b> "
string(63) " <dc:a xmlns:dc="myNS">c</dc:a> <dc:b xmlns:dc="myNS">d</dc:b> "
string(63) " <dc:a xmlns:dc="myNS">e</dc:a> <dc:b xmlns:dc="myNS">f</dc:b> "
string(63) " <dc:a xmlns:dc="myNS">g</dc:a> <dc:b xmlns:dc="myNS">h</dc:b> "