当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。