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

时间:2012-07-30 13:42:32

标签: php xml simplexml

  

可能重复:
  Getting SimpleXMLElement to include the encoding in output

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>

但我想将encoding="utf-8"之类的内容添加到xml标题中,以便我可以这样:

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

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

1 个答案:

答案 0 :(得分:-3)

阅读本文: -

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();
?>