PHP - xmlwriter_set_indent() 函数



定义和用法

XML 是一种用于在网络上共享数据的标记语言,XML 既可供人类阅读,也可供机器读取。XMLWriter 扩展内部具有 libxml xmlWriter API,用于编写/创建 XML 文档的内容。由此生成的 XML 文档是非缓存的且仅向前。

xmlwriter_set_indent() 函数接受 XMLWriter 类的对象和布尔值作为参数,并根据传递的布尔值设置输出 XML 文档的缩进打开/关闭。

语法

xmlwriter_set_indent($writer, $indentation);

参数

序号 参数及说明
1

writer(必填)

这是 XMLWriter 类的一个对象,表示您要修改/创建的 XML 文档。

2

indentation(必填)

这是一个布尔值,指定是否对输出文档进行缩进。

返回值

此函数返回一个布尔值,成功时为 TRUE,失败时为 FALSE。

PHP 版本

此函数首次引入于 PHP 5 版本,并在所有后续版本中均有效。

示例

以下示例演示了 xmlwriter_set_indent() 函数的用法:

<?php
   //Creating an XMLWriter
   $writer = new XMLWriter();

   //Opening a writer
   $uri = "result.xml";
   $writer = xmlwriter_open_uri($uri);

   //Starting the document
   xmlwriter_start_document($writer);

   //Starting an element
   xmlwriter_start_element($writer, 'Tutorial');

   //Setting indentation
   xmlwriter_set_indent($writer,TRUE);
   xmlwriter_set_indent_string($writer, "    ");
   
   //Creating XML elements
   xmlwriter_write_element($writer, 'name', 'JavaFX');  
   xmlwriter_write_element($writer, 'author', 'Krishna');  
   xmlwriter_write_element($writer, 'pages', '535');  

   //Ending the element
   xmlwriter_end_element($writer);

   //Ending the document
   xmlwriter_end_document($writer);
   print("XML Document Created");
?>

这将生成以下 XML 文档:

<?xml version="1.0"?>
<Tutorial>
   <Name>JavaFX</Name>
   <Author>Krishna</Author>
   <Pages>535</Pages>
</Tutorial> 

示例

以下是此函数在面向对象风格中的示例:

<?php
   //Creating an XMLWriter
   $writer = new XMLWriter();
   $uri = "result.xml";

   //Opening a writer
   $writer->openUri($uri);

   //Starting the document
   $writer->startDocument();

   //Starting an element
   $writer->startElement('Tutorial');

   //Setting indentation
   $writer->setIndent(TRUE);
   $writer->setIndentString("    ");
   
   //Creating XML elements
   $writer->writeElement('Name', 'JavaFX');  
   $writer->writeElement('Author', 'Krishna'); 
   $writer->writeElement('Pages', '535');  

   //Ending the element
   $writer->endElement();

   //Ending the document
   $writer->endDocument();
?> 

这将生成以下 XML 文档:

<?xml version="1.0"?>
<Tutorial>
   <Name>JavaFX</Name>
   <Author>Krishna</Author>
   <Pages>535</Pages>
</Tutorial>
php_function_reference.htm
广告