Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/246.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 更改根SimpleXML元素的文本_Php_Xml_Simplexml - Fatal编程技术网

Php 更改根SimpleXML元素的文本

Php 更改根SimpleXML元素的文本,php,xml,simplexml,Php,Xml,Simplexml,我正在尝试创建一个简单的包装函数,用于将我的错误输出到现有Flash应用程序的XML中。我已经读到,simplexmlement不一定用于创建新的XML文档,但到目前为止,它对我来说运行良好,我基本上是在替换串联字符串 到目前为止,我在迭代和添加/修改属性、值等方面没有遇到任何问题。在本例中,我希望看到我的输出如下所示: <ERROR>There is an error</ERROR> 有一个错误 但我看到了这一点: <ERROR> <ERROR

我正在尝试创建一个简单的包装函数,用于将我的错误输出到现有Flash应用程序的XML中。我已经读到,
simplexmlement
不一定用于创建新的XML文档,但到目前为止,它对我来说运行良好,我基本上是在替换串联字符串

到目前为止,我在迭代和添加/修改属性、值等方面没有遇到任何问题。在本例中,我希望看到我的输出如下所示:

<ERROR>There is an error</ERROR>
有一个错误
但我看到了这一点:

<ERROR>
  <ERROR>There is an error</ERROR>
</ERROR>

有一个错误
代码如下:

$msg = 'There is an error';    
$xmlstr = "<ERROR></ERROR>";
$sxml = new SimpleXMLElement($xmlstr);
$sxmlErr = $sxml->ERROR = $msg;
echo $sxml->asXML();
$msg='有一个错误';
$xmlstr=“”;
$sxml=新的simplexmlement($xmlstr);
$sxmlErr=$sxml->ERROR=$msg;
echo$sxml->asXML();

似乎使用
$obj->node
语法会创建一个子节点。我可以实例化一个
simplexmlement
的唯一方法是传递父节点。

结果是预期的。您的
$sxml
是根节点,例如
-使用对象操作符将导航到子元素(如果存在)或添加该名称的新元素(如果不存在)。由于根错误节点下没有错误元素,因此添加了它

改为通过索引访问根节点:

$msg = 'There is an error';
$xmlstr = "<ERROR></ERROR>";
$sxml = new SimpleXMLElement($xmlstr);
$sxmlErr = $sxml[0] = $msg;
echo $sxml->asXML();
$msg='有一个错误';
$xmlstr=“”;
$sxml=新的simplexmlement($xmlstr);
$sxmlErr=$sxml[0]=$msg;
echo$sxml->asXML();
避免陷入根元素陷阱的一个好方法是使用根元素的名称作为保存它的变量名,例如

$error = new SimpleXMLElement('<ERROR/>');
$error[0] = 'There is an Error';
echo $error->asXML();
$error=新的SimpleXMLElement(“”);
$error[0]=“有错误”;
echo$error->asXML();

另请参见

谢谢戈登!这太完美了!