使用SimpleXML从头开始创建XML对象 [英] Using SimpleXML to create an XML object from scratch

查看:95
本文介绍了使用SimpleXML从头开始创建XML对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用PHP的SimpleXML函数从头开始创建XML对象?浏览功能列表,可以通过一种方法将现有的XML字符串导入一个对象,然后可以对其进行操作,但是,如果我只是想从头开始以编程方式生成XML对象,什么是最好的方法?

Is it possible to use PHP's SimpleXML functions to create an XML object from scratch? Looking through the function list, there's ways to import an existing XML string into an object that you can then manipulate, but if I just want to generate an XML object programmatically from scratch, what's the best way to do that?

我发现您可以使用simplexml_load_string()并传入所需的根字符串,然后您有了一个可以通过添加子代进行操作的对象……尽管这似乎有点hack,因为在加载之前,我实际上必须将一些XML硬编码到字符串中.

I figured out that you can use simplexml_load_string() and pass in the root string that you want, and then you've got an object you can manipulate by adding children... although this seems like kind of a hack, since I have to actually hardcode some XML into the string before it can be loaded.

我已经使用 DOMDocument函数完成了此操作,尽管它是有点令人困惑,因为我不确定DOM与创建纯XML文档有什么关系……所以也许它的名字很糟糕:-)

I've done it using the DOMDocument functions, although it's a little confusing because I'm not sure what the DOM has to do with creating a pure XML document... so maybe it's just badly named :-)

推荐答案

可以.例如

<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>

输出

<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
    <content type="latest"/>
</news>

玩得开心.

这篇关于使用SimpleXML从头开始创建XML对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆