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


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

XMLReader::next()函數是PHP中的內置函數,用於將光標移到下一個跳過所有子樹的節點。此函數的另一種用法是它接受直接移動到元素的節點名稱。

用法:

bool XMLReader::next( string $localname )

參數:該函數接受單個參數$localname,該參數保存要移動到的下一個節點的名稱。



返回值:如果成功,則此函數返回TRUE;如果失敗,則返回FALSE。

以下示例程序旨在說明PHP中的XMLReader::next()函數:

程序1:在此程序中,我們將遍曆XML樹。
文檔名稱: data.xml

<?xml version="1.0" encoding="utf-8"?> 
<div1> 
    <h1> Foo Bar </h1> 
    <div2> 
        <h1> Foo Bar </h1> 
    </div2> 
</div1>

文檔名稱: 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->next(); 
  
  
// Print name of element 
echo "Before:<br> We are currently"
   . " at:$XMLReader->name<br>"; 
  
// Move to next node which is 
// text "Foo Bar" 
$XMLReader->next(); 
  
// Move to next element 
// which is div2 
$XMLReader->next(); 
  
// Print name of element 
echo "After:<br> We are currently"
    . " at:$XMLReader->name"; 
?>

輸出:
之前:

We are currently at:h1

後:

We are currently at:div2

程序2:在此程序中,我們將移至XML樹中的特定節點。

文檔名稱:data.xml

<?xml version="1.0" encoding="utf-8"?> 
<div1> 
    <h1> Foo Bar </h1> 
    <div2> 
        <h1> Foo Bar </h1> 
    </div2> 
    <div3> Hello </div3> 
</div1>

文檔名稱: 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 subtrees of div1 
$XMLReader->read(); 
$XMLReader->read(); 
$XMLReader->next("div2"); 
  
// Print name of element 
echo "Before:<br> We are currently"
      . "at:$XMLReader->name<br>"; 
  
// Move to next node which is 
// text "Foo Bar" 
$XMLReader->next(); 
  
// Move to next element which is div2 
$XMLReader->next(); 
  
// Print name of element 
echo "After:<br> We are currently"
    . " at:$XMLReader->name"; 
?>

輸出:
之前:

We are currently at:div2

後:

We are currently at:div3

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




相關用法


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