Это заголовок

DOMDocument::saveXML

Создаёт XML-документ из представления DOM. Эту функцию обычно вызывают после построения нового DOM-документа, как показано в примере ниже.

Список параметров

Используйте этот аргумент для вывода только определённого узла без объявления XML, а не всего документа целиком.

Дополнительные настройки. На данный момент поддерживается только LIBXML_NOEMPTYTAG.

Возвращаемые значения

Возвращает XML или false в случае возникновения ошибки.

Ошибки

DOM_WRONG_DOCUMENT_ERR

Возникает, если node принадлежит другому документу.

Примеры

Пример #1 Сохранение DOM-дерева в виде строки

$doc = new DOMDocument ( ‘1.0’ );
// мы хотим красивый вывод
$doc -> formatOutput = true ;

$root = $doc -> createElement ( ‘book’ );
$root = $doc -> appendChild ( $root );

$title = $doc -> createElement ( ‘title’ );
$title = $root -> appendChild ( $title );

$text = $doc -> createTextNode ( ‘Это заголовок’ );
$text = $title -> appendChild ( $text );

echo «Сохранение всего документа:\n» ;
echo $doc -> saveXML () . «\n» ;

echo «Сохранение только заголовка:\n» ;
echo $doc -> saveXML ( $title );

Результат выполнения данного примера:

Сохранение всего документа:    Сохранение только заголовка:  

Смотрите также

  • DOMDocument::save() — Сохраняет XML-дерево из внутреннего представления в файл
  • DOMDocument::load() — Загрузка XML из файла
  • DOMDocument::loadXML() — Загрузка XML из строки

User Contributed Notes 17 notes

How to display two tags when the node content is empty.

$dom = new \ DOMDocument ( ‘1.0’ );
$document = $dom -> createElement ( ‘document’ );
$document = $dom -> appendChild ( $document );
$head = $dom -> createElement ( ‘title’ , ‘this is title’ );
$content = $dom -> createElement ( ‘content’ , » );
$document -> appendChild ( $head );
$document -> appendChild ( $content );
echo $dom -> saveXML ();
?>

In XML, they are considered exactly the same thing, and any parser should recognize both forms.However, you can write it this way if you still need it

echo $dom -> saveXML ( $dom -> documentElement , LIBXML_NOEMPTYTAG );
?>

Example 1:

It took some searching to figure this one out. I didn’t see much in the way of explaining this glitch in the manual thus far. (For PHP5 I believe)

formatOutput = true; appears to fail when the origin of the DOM came from a file via load(). EX:

$dom = new DOMDocument ();
$dom -> load ( «test.xml» );
$dom -> formatOutput = true ;

$new_tag = $dom -> createElement ( ‘testNode’ );
$new_tag -> appendChild (
$dom -> createElement ( ‘test’ , ‘this is a test’ ));
$dom -> documentElement -> appendChild ( $new_tag );

printf ( «

%s

» , htmlentities ( $dom -> saveXML ()));
?>

Will not indent the output and will display the modified nodes all in one long line. Makes for editing a config.xml a bit difficult when saving to a file.

By adding the preserveWhiteSpace = false; BEFORE the load() the formatOutput works as expected. EX:

Читайте также:  Python сколько оперативной памяти

$dom = new DOMDocument ();
$dom -> preserveWhiteSpace = false ;
$dom -> load ( «test.xml» );
$dom -> formatOutput = true ;

$new_tag = $dom -> createElement ( ‘testNode’ );
$new_tag -> appendChild (
$dom -> createElement ( ‘test’ , ‘this is a test’ ));
$dom -> documentElement -> appendChild ( $new_tag );

printf ( «

%s

» , htmlentities ( $dom -> saveXML ()));
?>

CAUTION: If your loaded xml file (test.xml) has an empty root node that is not shortened or has no children this will NOT work.

if you are storing multi-byte characters in XML, then saving the XML using saveXML() will create problems. It will spit out the characters converted in encoded format.

$str = domdoc -> saveXML (); // gives «&x#1245;» some encoded data
?>

Instead do the following

$str = domdoc -> saveXML ( domdoc -> documentElement ); // gives «保存しました» correct multi-byte data
?>

When you save whole document:
DOMDocument->saveXML() produces string in encoding defined in property DOMDocument->encoding.

When you save only one node:
DOMDocument->saveXML(DOMNode) produces always string in UTF-8.

Quick tip to minimize memory when generating documents with DOM.

Rather than using
$xmlStr = DOMDocument->saveXML();
echo $xmlStr;

to dump a large DOM to the output buffer, use a PHP output stream, as in

A lot of memory will be saved when generating large DOMs.

The simpliest (and probably the fastest) way to strip an XML declaration () out of output document, is to output child nodes of DOMDocument separately:

$document = new DOMDocument ();
$document -> load ( ‘/some/file.xml’ );

// this will also output doctype and comments at top level
foreach( $document -> childNodes as $node )
$result .= $document -> saveXML ( $node ). «\n» ;

?>

This might be userful when dealing with browser compatibility issues, for example, well known problem with valid XHTML in IE6.

Comment to `devin at SPAMISBAD dot tritarget dot com»s post:

Thanks for pointing out the pitfalls of `formatOutput’ vs. `load*()’. This has certainly saved me from some possible surprises.

I think the seemingly strange behaviour can be explained. Warning: The following stuff is mostly based on deductions and experiments. Much less on studying the sources and specs (I’m not sure some of these would provide answer anyway, at least not easily).

As you point out, `preserveWhiteSpace’ must be set before loading the DOM from the source string (I’m working with `loadXML()’ but I believe the situation should be the same with `load()’ you used). This looks logical, as this property seems to control the parsing and DOM creation process during which text nodes containing the whitespace are either included or dropped. This can be proven by dumping the DOM structure and comparing the results based on the value of `preserveWhiteSpace’. With `preserveWhiteSpace’ set to `FALSE’, no text nodes containing whitespace will be present in the returned DOM. When this property is `TRUE’, these nodes will be present.

Note: When speaking about the whitespace in the previous paragraph, we’re most certainly speaking about so called `whitespace in element content’ or `element content whitespace’, if I’m not mistaken. See also my comment in the notes of `DOMText->isWhitespaceInElementContent()’ method.

Читайте также:  Сервера на css v34 вход

As for the mysterious effect on the output of `saveXLM()’, I think the explanation lies in the presence or absence of the above mentioned whitespace text nodes. This was also proven by experiments: After adding such a node into a DOM which contained none (the DOM was created using `loadXML()’ with `preserveWhiteSpace’ set to `FALSE’), the output formatting got affected in a such a way, the formatting got lost for the rest of the document after the added node. I think the presence of whitespace text nodes forces such rendering, that the content of these nodes is used to separate adjoining nodes thus disabling default formatting. Only when there are no such text nodes present, the ouput formatting takes effect (provided the `formatOutput’ is set to `TRUE’, of course).

Well, the thing I don’t really understand is how you did get an output of a signle line with `formatOutput’ set to `TRUE’. This has happened to me when no whitespace text nodes were present (ie. when loading the XML with `preserveWhiteSpace’ set to `FALSE’) *and* with `formatOutput’ set to *`FALSE’* (with the opposite value of `formatOutput’, the formatting should do it’s work and you should not end up with just one line). But I haven’t seen your source. Perhaps you had whitespace nodes containing no new-lines in your DOM?

As for the CAUTION about root element, I didn’t see any problems with empty root element neither in shortened nor full form. What did you have in mind, when you said it `WORKS’ or `DOES NOT WORK’?

Источник

Creation of XML File in PHP with SimpleXML

XML Stands for Extensible Markup Language. A markup language is used to annotate text or add additional information.

XML is a universal format for structured documents and data on web. It allows you to separate content from formatting.

Note :- I assume that you have basic idea what XML Files are.

Starting with the tutorial :-

As we are going to generate XML File with SimpleXML, there is a basic requirement to use SimpleXML.

Prerequisites :

This extension requires the libxml PHP extension. This means that passing in –enable-libxml is also required, although this is implicitly accomplished because libxml is enabled by default. The SimpleXML extension requires PHP 5.0 .

Installation :

This extension is enabled by default. It may be disabled by using the following option at compile time: –disable-simplexml

Note: Before PHP 5.1.2, –enable-simplexml is required to enable this extension.

1. Creating Object of SimpleXML :

$xmlstr =     Azhar Imran Hashmi  Sangeeta Nargis Fakri   All is revealed in this controversial spoof of a documentary. PHP solves all my web problems  7 5   XML; //SimpleXML Object created $movies = new SimpleXMLElement($xmlstr);

2. Adding child Node :

Adds child element to XML node

addChild ( string $name [, string $value [, string $namespace ]] )

It takes following parameters,

  1. Name:- Name of the child node to be added
  2. Value:- Value of the child node (optional)
  3. Namespace:- Namespace to which the child element belongs (optional)
Читайте также:  Serial port raspberry python

Returns:- The addChild method returns a SimpleXMLElement object representing the child added to the XML node.

$xmlstr = " "; //Creating SimpleXML Object $movies = new SimpleXMLElement($xmlstr); //Adding child to movies node (name:actorName and value:Brad Pitt) $movies->addChild(‘actorName’,’Brad Pitt’);

3. Adding attribute to node :

Adds an attribute to XML element

addAttribute (string $name [, string $value [, string $namespace ]] )

It takes following parameters,

  1. Name :- Name of the attribute to add
  2. Value :- Value of the attribute (optional)
  3. Namespace :- Namespace to which the attribute belong (optional)

Returns :- No value is returned.
Example :-

$xmlstr=" "; //Creating SimpleXML Object $newsXML = new SimpleXMLElement($xmlstr); //Setting the newsPagePrefix attribute and its value to the news node $newsXML->addAttribute('newsPagePrefix', 'Times of India');

4. Saving XML File :

Returns well-formed XML string based on SimpleXML element.

asXML ([string $filename] ) OR saveXML ([string $filename] )

It takes following parameter,

The asXML method formats the parent object’s data in XML version 1.0.

Returns :- If the filename isn’t specified, this function returns a string on success and FALSE on error. If the parameter is specified, it returns TRUE if the file was written successfully and FALSE otherwise.

//Saving XML File $movies->asXML(); OR $movies->saveXML(); OR $movies->asXML(“movie-details.xml”);

5. Using CDATA Section:

What is CDATA ? what does it do ? How it is useful ?

CDATA stands for Character Data and it means that the data in between these strings includes data that could be interpreted as XML markup.

We can also say that, CDATA are defined as blocks of text that are not parsed by the parser, but are otherwise recognized as markup.

The predefined entities such as <, >, and & require typing and are generally difficult to read in the markup. In such cases, CDATA section can be used. By using CDATA section, you are commanding the parser that the particular section of the document contains no markup and should be treated as regular text.

Now to use CDATA in Your XML File, You need to create a class extending the SimpleXMLElement class and in that create a wrapper/helper function for CDATA.

Example Using CDATA Section :-

//Saving XML File $leadRootNode->saveXML(“lead-details.xml”);

Output :- File Name : lead-details.xml

//Creating custom class and extending the SimpleXMLElement Class Class SimpleXMLElementExtended extends SimpleXMLElement < /* * Adds a child with $value inside CDATA */ public function addChildWithCDATA($name, $value = NULL) < $new_child = $this->addChild($name); if ($new_child !== NULL) < $node = dom_import_simplexml($new_child); $no=$node->ownerDocument; $node->appendChild($no->createCDATASection($value)); > return $new_child; > > $xmlstr =" ";

**Note :- As we are using CDATA we will be creating object of SimpleXMLElementExtended Class.

For XML File Generation using SimpleXML

Источник

Оцените статью