如何使用SimpleXMLElement将属性添加到xml头中


How to add attribute to xml header using SimpleXMLElement

可能重复:
使SimpleXMLElement在输出中包含编码

PHP:

$xml = new SimpleXMLElement("<Title0></Title0>");
$xml->Title1='Some Text  1';
$output = $xml->asXML('mak.xml');

XML输出:

<?xml version="1.0"?>  
<Title0>
    <Title1>Some Text 1</Title1>
</Title0>

但我想在xml头中添加类似encoding="utf-8"的属性,这样我就可以有这样的东西:

<?xml version="1.0" encoding="utf-8" ?>  
<Title0>
    <Title1>Some Text 1</Title1>
</Title0>

我不想在输出文件中使用find和replace之类的东西。

阅读以下内容:--

http://php.net/manual/en/simplexml.examples-basic.php

试试这个:-

示例#10添加元素和属性

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
$character = $movies->movie[0]->characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');
$rating = $movies->movie[0]->addChild('rating', 'PG');
$rating->addAttribute('type', 'mpaa');
echo $movies->asXML();
?>