Reputation: 33
I've got this problem:
This is my .xml
<listado>
<sucursal> //first sucursal
<idSuc>1</idSuc>
<nombre>Peru</nombre>
</sucursal>
.//here there are 48 more “sucursal”--- 50 nodes total...
<sucursal>
<idSuc>53</> // last sucursal
<nombre>Abasto</nombre>
</sucursal>
</listado>
…..
I need to take (in variable php) not the count of the “sucursal” or “idSuc” (in this case “50”) but the value of the last “idSuc” ( in my case “53”)... I don't want to set the "idSuc" as atribute of "sucursal" ( xe) because they are datums take from a form ($_POST), etc..
I'm trying with “xpath” and “lastchild”, etc... but nothing... and “length” is ok but it's not what I need.. because it's useless in my work.
for ex:
<?php $datos= new DOMDocument();
$datos->load('datos2.xml');
$sucs = $datos->getElementsByTagName("sucursal");
$id = $datos->getElementsByTagName("idSuc"); ?> ..
?>
and then in the form where I need this "value":
<form method="POST"....> <input name="idSuc" value="<?php print_r($id->length+1)?>"..>
Also with:
value="<?php print_r($id->last_child.value+1)?>"
-- in the form --$elements->xpath('listado/sucursal [last()]');
and then I try to print $elements
in the form.... nothingAnd many others that I dont remember now because I remove all.. :(
Please,... somebody can help me!!.. or give just an diferent idea... ??!
thanks a lot!!... I had working with this 4 days and nothig!! :(
Upvotes: 0
Views: 320
Reputation: 20748
Try something like:
$xpath = new DOMXpath($datos);
$lastIdSuc = $xpath->query('/listado/sucursal[last()]/idSuc')->item(0)->nodeValue;
and
<input name="idSuc" value="<?php echo $lastIdSuc; ?>">
Upvotes: 1
Reputation: 489
First of all, you should load the XML like this:
$datos->load('datos2.xml', LIBXML_NOBLANKS);
This way, all blank nodes (even empty spaces) are ignored. Now, this line
$sucs = $datos->getElementsByTagName("sucursal");
gives you all the sucursal nodes as a DOMNodeList, so, to get the last one, you do this:
$last = $sucs->item($sucs->length - 1);
which gives you a DOMNode object. Now you need its children, which you can get like this:
$suc_children = $last->childNodes;
childNodes is another DOMNodeList. If you are sure that the element idSuc will always be the first element, then you get it using
$id_suc = $suc_children->firstChild->nodeValue;
First check if there are any $suc_children, otherwise you will get no ID:
if($suc_children->hasChildNodes())
$id_suc = $suc_children->firstChild->nodeValue;
// You could do $suc_children->item(0)->nodeValue too
If you are not sure that the first element will be idSuc, then you will have to iterate through the DOMNodeList to find it.
Upvotes: 0