Using foreach to avoid redundant XPath form processing code

My XML looks like this:

<?xml version="1.0" encoding="UTF-8"?>
        <area name="Rocket">
                <trail name="Trail 1" status="CLOSED" />
                <trail name="Trail 2" status="CLOSED" />
                <trail name="Trail 2" status="CLOSED" />

I am successfully able to edit the attributes using the following code:

<script src=""></script>
 $xml = new DOMDocument('1.0', 'utf-8');
 $xml->formatOutput = true; 
 $xml->preserveWhiteSpace = false;

 $xpath = new DOMXpath($xml);

 $asstatus = $xpath->query("//facilities/areas/area[@name='Rocket']/trails/trail[@name='Trail 1']/@status")->item(0);


 if (isset($_POST['submit']))
$asstatus->nodeValue = $_POST['asstatusform'];


<form method="POST" action=''>
<!--Trail 1-->
<span class="title">Trail 1</span> <span class="title">Status</span>
<select name="asstatusform" >
<option selected value="<?php echo $asstatus->nodeValue  ?>"><?php echo $asstatus->nodeValue  ?></option>
<option value="OPEN">OPEN</option>
<option value="CLOSED">CLOSED</option>
<option value="RACING CLOSURE">RACING CLOSURE</option>
<input name="submit" type="submit" value="Save" />

What I'm wondering if there's an easy way to change it to use foreach so that I don't have to create a new query and form for each separate trail name. I've tried a few variations thus far, to no great success.

1 answer

  • answered 2019-06-12 05:15 Nigel Ren

    A simple combination of using XPath to fetch the list of trails and then for each trail fetching the attributes for the display.

    foreach ( $xpath->query("//trails/trail") as $trail )   {
        echo $trail->getAttribute("name")."/".

    You can decide on how you want to display this data - separate forms/table etc.