无法使用PHP的SimpleXML将名称空间添加到属性 [英] Unable to add namespace to an attribute with PHP's SimpleXML

查看:115
本文介绍了无法使用PHP的SimpleXML将名称空间添加到属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在下面尝试将xmlns:i添加为属性时,我正在创建Atom提要-

I am creating an Atom feed, when I tried below to add xmlns:i as an attribute -

$node->addAttribute("xmlns:i","http://www.w3.org/2001/XMLSchema-instance"); 

我将其作为输出-

i="http://www.w3.org/2001/XMLSchema-instance"

"xmlns:"部分被切除.我需要转义:字符吗?还是他们以其他方式添加此命名空间?

"xmlns:" part was cut off. do I need to escape the :-character? Or is they any other way to add this namespace?

推荐答案

如果要将名称空间/前缀i中的属性添加到$ node,则无需事先声明名称空间.只需使用addAttribute()的第三个参数为您在第一个参数中使用的前缀提供名称空间uri.

If you want to add an attribute from the namespace/prefix i to $node don't bother declaring the namespace beforehand. Just use the third parameter of addAttribute() to provide the namespace uri for the prefix you're using in the first parameter.

$node = new SimpleXMLElement('<root></root>');
$node->addAttribute("i:somename", "somevalue", 'http://www.w3.org/2001/XMLSchema-instance'); 
echo $node->asXml();

打印

<?xml version="1.0"?>
<root xmlns:i="http://www.w3.org/2001/XMLSchema-instance" i:somename="somevalue"/>

如果不需要属性本身,则可以使用unset()将其删除,保留名称空间声明.

If the attribute itself isn't needed, you can then remove it with unset(), leaving the namespace declaration.

unset($node->attributes('i', TRUE)['somename']);

这篇关于无法使用PHP的SimpleXML将名称空间添加到属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆