【发布时间】:2023-02-08 02:10:22
【问题描述】:
因为我想学习 PHP,所以我正在尝试构建一个简单的 Web 应用程序。
我有这段代码:
// create objects
$object = new Post();
$object->name = 'Post no. 1';
$object->content = "My glorious content\nwritten in two lines!";
$object->fixed = 'True';
$object->picture = 'pathtoimg1.png';
$posts[] = $object;
$object = new Post();
$object->name = 'Post no. 2';
$object->content = 'Content.';
$object->fixed = 'False';
$object->picture = 'pathtoimg2.bmp';
$posts[] = $object;
// set xml
$postsXml = new SimpleXMLElement('<arrayOfPost></arrayOfPost>');
foreach($posts as $post){
$element = $postsXml->addChild('post');
$element->addChild('name', $post->name);
$element->addChild('content', $post->content);
$element->addChild('fixed', $post->fixed);
$element->addChild('picture', $post->picture);
}
echo $postsXml->asXML();
它创建了这个 XML:
$xmlString = '<?xml version="1.0"?>
<arrayOfPost><post><name>Post no. 1</name><content>My content
written in two lines!</content><fixed>True</fixed><picture>pathtoimg1.png</picture></post><post><name>Post no. 2</name><content>Content.</content><fixed>False</fixed><picture>pathtoimg2.bmp</picture></post></arrayOfPost>';
那就是我正在使用的课程:
class Post {
// Properties
public $name;
public $content;
public $fixed;
public $picture;
}
如何再次将 XML 字符串解析为对象“Post”数组?
【问题讨论】:
-
为什么要为 XML 而烦恼?如果您的意图只是序列化数据,则可以使用 JSON 在一行中完成所有这些操作。