如何使用 PHP5 将子节点添加到 XML 文件中的最后一个节点?
正在尝试做的事情
这就是我目前
<sessions>
<session>
<event>milk</event>
</session>
<session>
<event>graze</event>
</session>
</sessions>
:我想转到最后一个“会话”节点并添加一个新事件,
<event>health treatment</event>
因此它看起来像:
<sessions>
<session>
<event>milk</event>
</session>
<session>
<event>graze</event>
<event>health treatment</event>
</session>
</sessions>
我尝试了 simpleXML 的 xpath 并注册了路径名,我找到了一些示例这个网站但没有成功 我更喜欢使用 simpleXML,但如果 dom 是唯一的解决方案,那么我会使用它,我没有设法在 dom 中做到这一点,
这里是我的脚本(我在实验时注释了一些位):
<?php
$session = $_POST['session'];
$event = $_POST['event'];
$xml = simplexml_load_file("sessions.xml");
//$xml->registerXPathNamespace('o', 'http://obix.org/ns/schema/1.0');
$sxe = new SimpleXMLElement($xml->asXML());
if(isset($session)){
$item = $sxe->addChild("session");
}else{
list($item) = $xml->xpath('/sessions/session[last()]');
$item->name = 'Jane Smith';
//$item = $sxe->children('session[last()]');
//$xpath = '/o:sessions/o:session[last()]';
//$item = $xml->xpath($xpath);
}
$item->addChild("event", $event);
$sxe->asXML("sessions.xml");
?>
或者如果你知道如果有更好的方法,请告诉我。
here's what i'm trying to do
i currently have:
<sessions>
<session>
<event>milk</event>
</session>
<session>
<event>graze</event>
</session>
</sessions>
i want to go to the very last "session" node and add a new event
<event>health treatment</event>
so it'd look like:
<sessions>
<session>
<event>milk</event>
</session>
<session>
<event>graze</event>
<event>health treatment</event>
</session>
</sessions>
i tried simpleXML's xpath and registering the pathname, i found some examples on this site but no success
i'd prefer to use simpleXML but if dom's the only solution then i'll use it, i did not manage to do this in dom either
here's my script (i commented some bits out for when i was experimenting):
<?php
$session = $_POST['session'];
$event = $_POST['event'];
$xml = simplexml_load_file("sessions.xml");
//$xml->registerXPathNamespace('o', 'http://obix.org/ns/schema/1.0');
$sxe = new SimpleXMLElement($xml->asXML());
if(isset($session)){
$item = $sxe->addChild("session");
}else{
list($item) = $xml->xpath('/sessions/session[last()]');
$item->name = 'Jane Smith';
//$item = $sxe->children('session[last()]');
//$xpath = '/o:sessions/o:session[last()]';
//$item = $xml->xpath($xpath);
}
$item->addChild("event", $event);
$sxe->asXML("sessions.xml");
?>
or if you know a better way to do this then please let me know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 SimpleXMLElement::count()< 轻松跳转到元素的最后一个子元素/a>
例如
You can easily jump to the last child of an element using SimpleXMLElement::count()
For example