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

如何在PHP中替换Spatie array-to-xml生成的<numeric_*>为<singlenews>?

解决Spatie array-to-xml生成<numeric_*>标签替换为<singlenews>的问题

嘿,我知道你卡在这儿了!咱们来搞定这个标签替换的问题——你现在遇到的<numeric_0>、<numeric_1>这类标签,是因为Spatie的array-to-xml库对索引数组默认会生成带数字后缀的标签名。要换成你想要的<singlenews>,有两个简单直接的办法:

方法一:用库的numericTag配置指定标签名

这是最直接的方式,直接告诉库索引数组的元素应该用什么标签:

public function exportNews(){ 
    $news = News::all()->toArray(); 
    $result = ArrayToXml::convert($news, [
        'rootElementName' => 'root', // 可选,默认就是root,明确写出来更清晰
        'numericTag' => 'singlenews', // 重点:这里设置索引数组元素的标签名
    ]); 
    return response($result)->header('Content-Type', 'text/xml'); 
}

方法二:构造嵌套数组结构

把所有新闻数据放在singlenews这个键名下,库会自动为每个数组元素生成<singlenews>节点:

public function exportNews(){ 
    $news = News::all()->toArray(); 
    $result = ArrayToXml::convert(['singlenews' => $news]); 
    return response($result)->header('Content-Type', 'text/xml'); 
}

效果验证

不管用哪种方法,最终生成的XML都会变成你想要的样子:

<root> 
    <singlenews> 
        <id>14</id> 
        <created_at>2019-08-25 19:19:07</created_at> 
        <updated_at>2019-08-25 20:02:46</updated_at> 
        <title>Lorem ipsum</title> 
        <body>imbardata</body> 
        <abstract>fondamentale</abstract> 
        <file_url> foo </file_url> 
        <author_name/> 
    </singlenews> 
    <singlenews> 
        <id>15</id> 
        <created_at>2019-10-01 22:14:55</created_at> 
        <updated_at>2019-10-01 22:14:55</updated_at> 
        <title>132</title> 
        <body>132</body> 
        <abstract>132</abstract> 
        <file_url> foo </file_url> 
        <author_name>Boris</author_name> 
    </singlenews> 
    <!-- 更多<singlenews>节点 -->
</root>

为啥之前的__numeric没用?因为这个参数是用来让数组不生成带索引的包裹标签,而不是用来自定义标签名的,所以才会出现你看到的默认numeric_*格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:15:56