php - is there a max_value function for xml child node?


thanks you all for helping me to learn xml+php!

I want to make an Autoincrement for the id child node. in my createxml.php i'm the one who enter the id.. i want to be able to know what is the maxium value of all id's and then the id=max_value++

I hope i explain my self well.

this is the events.xml file:


and this is how i adding new child nodes to the xml..



header("Content-type: text/html; charset=utf-8");

$record = array(
    'id' => $_POST['id'],
    'event' => $_POST['event'],
    'eventDate' => $_POST['eventDate'],
    'desc' => $_POST['desc'],

$doc = new DOMDocument();
$doc->load( 'events.xml' );
$doc->formatOutput = true;
$r = $doc->getElementsByTagName("events")->item(0);
$b = $doc->createElement("record");

$id = $doc->createElement("id");
    $doc->createTextNode( $record["id"] )
$b->appendChild( $id );

$event = $doc->createElement("event");
    $doc->createTextNode( $record["event"] )
$b->appendChild( $event );

$eventDate = $doc->createElement("eventDate");
    $doc->createTextNode( $record["eventDate"] )
$b->appendChild( $eventDate );

$desc = $doc->createElement("desc");
    $doc->createTextNode( $record["desc"] )

$b->appendChild( $desc );
$r->insertBefore( $b,$r->firstChild );


    header("Location: {$_SERVER['HTTP_REFERER']}");    

Thanks all for helping!




Something like this, perhaps:

$ids = array();
foreach($doc->getElementsByTagName('id') as $id) {
    $ids[] = (int) $id->nodeValue;
$max_id = max($ids);

Edit Possibly a nicer way is with XPath:

$xpath = new DOMXPath($doc);
$max_id = $xpath->query('//events/record[not(../record/id > id)]/id')->item(0)->nodeValue;



The best tool for finding the max id is XPath. If you were using a SimpleXML object and the records were known to be in order by id, then getting the id would go something like this:

$xml = simplexml_load_string($xmlstring);
$xpath="(//[email protected])[last()]";

If your results are unordered, then the XPath expression can get a bit hairy, but it's still likely to be a lot faster than looping through the results.

People are also looking for solutions to the problem: curl - Echo messages while php script still executes


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.