SimpleXMLElement 影响(在写入上下文中传递属性)
我遇到了 SimpleXML 的问题。就像在官方文档中一样,我想这样做:
<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
$movies->movie[0]->characters->character[0]->name = 'Miss Coder';
echo $movies->asXML();
?>
但我的代码是:
<?php
public function renderMarker($xml, &$html)
{
$html = ((string) $html) . 'Text to add';
}
?>
with:
$html = object(SimpleXMLElement)#185 (1) {
["@attributes"]=>
array(1) {
["id"]=>
string(5) "title"
}
}
但是当我这样做时,我得到了 $html = string(12) "Text to add"
作为结果。 有谁知道这个问题的解决方法。 提前致谢。
I've got an issue with SimpleXML. Like in the official documentation, I want to do this :
<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
$movies->movie[0]->characters->character[0]->name = 'Miss Coder';
echo $movies->asXML();
?>
But my code is :
<?php
public function renderMarker($xml, &$html)
{
$html = ((string) $html) . 'Text to add';
}
?>
with :
$html = object(SimpleXMLElement)#185 (1) {
["@attributes"]=>
array(1) {
["id"]=>
string(5) "title"
}
}
But when I do this, I've got $html = string(12) "Text to add"
as a result.
Does anybody knows a workarround for this.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您尝试实现的目标不起作用,并且 SimpleXML 没有解决方案。
每个 SimpleXML 对象都具有动态属性。您可以像访问它们一样访问它们,就像它们是对象的属性一样,但事实上,每次访问它们时,要么给出属性的返回值(读取),要么更新其他内容(写入)。
但是,如果像您一样将此类属性传递给函数,则您只传递了实际返回值(来自读取),而不是属性本身。
简化的示例不起作用,因为
$xml->title
没有作为变量传递到set_property
函数中(不需要添加引用,它不有所作为):输出:
如所写,没有简单的解决方法。一种解决方法是您自己创建一个 SimpleXMLProperty 对象,您可以在函数参数中传递该对象:
输出:
它封装属性并根据调用的 get 或 set 函数在读写上下文中访问它 (演示)。
但对于您构建的内容,查看 DomDocument 可能会更好。它有一个更加标准化的 DOM 接口,并且您实际上可以传递已经存在的对象,例如文本节点。
What you try to achieve does not work and there is no solution for that with SimpleXML.
Each SimpleXML object has dynamic properties. You access them as-if they were a property of an object, but infact, each time you access them, either the property's return value is given (reading) or something else is updated (writing).
However, if you pass such properties to a function like you did, you only passed the actual return value (from reading) and not the property itself.
Simpliefied example which does not work, because
$xml->title
is not passed as variable into theset_property
function (there is no need to add a reference, it does not make a difference):Output:
As written, there is no easy workaround for it. One workaround is that you create yourself a SimpleXMLProperty object that you can pass around in function parameters:
Output:
It encapsulates the property and accesses it in read and write context depending on the get or set function called (Demo).
But for what you build, it might be a better thing to look into DomDocument instead. It has a much more standardized interface to the DOM, and you actually pass objects already around, like text-nodes.