📜  PHP | XMLReader moveToElement()函数

📅  最后修改于: 2022-05-13 01:56:34.935000             🧑  作者: Mango

PHP | XMLReader moveToElement()函数

XMLReader::moveToElement()函数是PHP中的一个内置函数,用于将光标移动到当前属性的父元素。此函数可用于通过将其与XMLReader::moveToAttribute()函数结合来获取具有某些属性的元素。

句法:

bool XMLReader::moveToElement( void )

参数:此函数不接受任何参数。

返回值:此函数在调用此方法时如果成功则返回 TRUE,如果失败或未定位在属性上则返回 FALSE。

下面给出的程序说明了PHP中的XMLReader::moveToElement()函数

程序1:在这个程序中,我们将获取具有属性“attrib”的元素的名称

文件名: data.xml


    

Foo Bar

文件名:索引。 PHP

open('data.xml');
  
// Iterate through the XML nodes
// to reach the h1 node
$XMLReader->read();
$XMLReader->read();
$XMLReader->read();
  
// Move to attribute with name attrib
$XMLReader->moveToAttribute("attrib");
  
// Move cursor to the element of attribute
$XMLReader->moveToElement();
  
// Output the name of element to browser
echo $XMLReader->name;
?>

输出:

h1

程序2:在这个程序中,我们将获取所有具有属性“attrib”的元素的名称。

文件名: data.xml


    

Foo Bar

    

Foo Bar

    

Foo Bar

    

Foo Bar

文件名:索引。 PHP

open('data.xml');
  
// Iterate through the XML nodes
while ($XMLReader->read()) {
    if ($XMLReader->nodeType == XMLREADER::ELEMENT) {
  
        // Get the element name if attribute
        // name is "attrib"
        if ($XMLReader->moveToAttribute("attrib")) {
  
            // Move cursor to the element of attribute
            $XMLReader->moveToElement();
  
            // Output the value to browser
            echo $XMLReader->name . "
";         }        } } ?>

输出:

h1
h2

参考: https://www. PHP.net/manual/en/xmlreader.movetoelement。 PHP