开发者

How to add a child to the last node in an XML file using PHP5?

开发者 https://www.devze.com 2023-02-09 07:58 出处:网络
here\'s what i\'m trying to do i currently have: <sessions> <session> <event>milk</event>

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[开发者_StackOverflowlast()]');
$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.


You can easily jump to the last child of an element using SimpleXMLElement::count()

For example

$lastSession = $xml->session[$xml->session->count() - 1];
$lastSession->addChild('event', $event)
0

精彩评论

暂无评论...
验证码 换一张
取 消