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

查看:16
本文介绍了使用 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() 并传入你想要的根字符串,然后你就有了一个可以通过添加子项来操作的对象......虽然这看起来有点像黑客,因为在加载之前,我必须将一些 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天全站免登陆