當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


PHP XMLReader moveToElement()用法及代碼示例

XMLReader::moveToElement()函數是PHP中的內置函數,用於將光標移動到當前屬性的父元素。通過將此函數與XMLReader::moveToAttribute()函數結合使用,可以使用該函數來獲取具有某些屬性的元素。

用法:

bool XMLReader::moveToElement( void )

參數:此函數不接受任何參數。



返回值:調用此方法時,如果成功,此函數將返回TRUE,如果失敗或未定位在屬性上,則返回FALSE。

下麵給出的程序說明了PHP中的XMLReader::moveToElement()函數:

程序1:在此程序中,我們將獲得具有屬性“attrib”的元素的名稱

文檔名稱: data.xml

<?xml version="1.0" encoding="utf-8"?> 
<div> 
    <h1 attrib="value"> Foo Bar </h1> 
</div>

文檔名稱: index.php

<?php 
  
// Create a new XMLReader instance 
$XMLReader = new XMLReader(); 
  
// Open the XML file 
$XMLReader->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

<?xml version="1.0" encoding="utf-8"?> 
<div> 
    <h1 attrib="value1"> Foo Bar </h1> 
    <h2 attrib="value2"> Foo Bar </h2> 
    <h3 other="value"> Foo Bar </h3> 
    <h4 other="value"> Foo Bar </h4> 
</div>

文檔名稱: index.php

<?php 
  
// Create a new XMLReader instance 
$XMLReader = new XMLReader(); 
  
// Open the XML file 
$XMLReader->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 . "<br>"; 
        } 
  
    } 
} 
?>

輸出:

h1
h2

參考: https://www.php.net/manual/en/xmlreader.movetoelement.php




相關用法


注:本文由純淨天空篩選整理自gurrrung大神的英文原創作品 PHP | XMLReader moveToElement() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。