You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中将XML解析为Post对象数组?

将XML字符串解析为Post对象数组的PHP实现

我正在学习PHP,开发一个简易Web应用,已实现将Post对象数组转换为XML字符串的功能,相关代码及生成的XML内容如下:

创建Post对象并生成XML的代码

// 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>';

Post类定义

class Post {
  // Properties
  public $name;
  public $content;
  public $fixed;
  public $picture;
}

解析XML到Post对象数组的实现方法

// 若XML字符串经过HTML转义(如包含&lt;、&quot;等),需先解码
// $decodedXml = htmlspecialchars_decode($xmlString);
// $xml = new SimpleXMLElement($decodedXml);

// 直接加载原始XML字符串
$xml = new SimpleXMLElement($xmlString);
$posts = [];

// 遍历每个post节点,实例化Post对象并赋值属性
foreach ($xml->post as $postNode) {
    $post = new Post();
    // 强制转换为字符串,确保获取节点的文本内容
    $post->name = (string)$postNode->name;
    $post->content = (string)$postNode->content;
    $post->fixed = (string)$postNode->fixed;
    $post->picture = (string)$postNode->picture;
    
    $posts[] = $post;
}

// 输出验证结果
print_r($posts);

关键说明

  • 使用SimpleXMLElement加载XML字符串,通过$xml->post获取所有<post>节点;
  • 每个子节点(如<name>、<content>)需要强制转换为字符串,否则返回的是SimpleXMLElement对象而非实际文本内容;
  • 若XML字符串是经过HTML转义存储的(比如示例中显示的&lt;),需先用htmlspecialchars_decode()解码后再加载。

内容的提问来源于stack exchange,提问作者jjb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 23:00:26