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


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

XMLReader::moveToFirstAttribute()函數是PHP中的內置函數,用於將光標置於元素的第一個屬性上。當我們對一個元素有多個屬性並且想要獲取第一個屬性時,或者當我們要檢查一個元素是否具有任何屬性時,此函數很有用。

用法:

bool XMLReader::moveToFirstAttribute( void )

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



返回值:如果成功,此函數將返回TRUE,否則將返回FALSE。

以下示例說明了PHP中的XMLReader::moveToFirstAttribute()函數:

範例1:

  • data.xml
    <?xml version="1.0" encoding="utf-8"?> 
    <div> 
        <h1>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(); 
      
    // Checking if attribute is there or not 
    if ($XMLReader->moveToFirstAttribute()) { 
        echo "Attribute is there"; 
    } else { 
        echo "No, attributes."; 
    } 
    ?>
  • 輸出:
    No, attributes.

程序2:

  • data.xml
    <?xml version="1.0" encoding="utf-8"?> 
    <div> 
        <h1 attrib1="value1" 
            attrib2="value2" 
            attrib3="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 attrib3 
    $XMLReader->moveToAttribute("attrib3"); 
      
    // Print name of element 
    echo "Before:<br> We are currently "
          . "at:$XMLReader->name<br>"; 
      
    // Move to first attribute 
    $XMLReader->moveToFirstAttribute(); 
      
    // Print name of element 
    echo "After:<br> We are currently "
          . "at:$XMLReader->name"; 
    ?>
  • 輸出:
    Before:
    We are currently at:attrib3
    After:
    We are currently at:attrib1

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




相關用法


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