gpt4 book ai didi

PHP SimpleXMLElement addAttribute 命名空间语法

转载 作者:行者123 更新时间:2023-12-04 16:50:48 35 4
gpt4 key购买 nike

我是第一次使用 SimpleXMLElement,需要在我的 XML 中生成一行,如下所示:

<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

我之前没有对命名空间使用过 addAttribute 并且无法在这里使用正确的语法 - 我已经开始了:

$node = new SimpleXMLElement('< Product ></Product >');
$node->addAttribute("xmlns:", "xsd:", 'http://www.w3.org/2001/XMLSchema-instance');

但无法弄清楚如何更正此问题以获得适当的语法以生成所需的输出?

最佳答案

方案一:在前缀中添加前缀

<?php
$node = new SimpleXMLElement('<Product/>');
$node->addAttribute("xmlns:xmlns:xsi", 'http://www.w3.org/2001/XMLSchema-instance');
$node->addAttribute("xmlns:xmlns:xsd", 'http://www.w3.org/2001/XMLSchema');
echo $node->asXML();

输出:

<?xml version="1.0"?>
<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>

注意:这是一种解决方法,实际上并没有为属性设置命名空间,但如果您要回显/保存以归档结果就足够了

解决方案 2:将命名空间直接放在 SimpleXMLElement 构造函数中

<?php
$node = new SimpleXMLElement('<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>');
echo $node->asXML();

输出与方案一相同

解决方案 3(添加附加属性)

<?php
$node = new SimpleXMLElement('<Product/>');
$node->addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance", "xmlns");
$node->addAttribute("xmlns:xsd", 'http://www.w3.org/2001/XMLSchema', "xmlns");
echo $node->asXML();

输出添加额外的xmlns:xmlns="xmlns"

<?xml version="1.0"?>
<Product xmlns:xmlns="xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>

关于PHP SimpleXMLElement addAttribute 命名空间语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43565945/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com