Using foreach to avoid redundant XPath form processing code

My XML looks like this:

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

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

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
 <?php
 $xml = new DOMDocument('1.0', 'utf-8');
 $xml->formatOutput = true; 
 $xml->preserveWhiteSpace = false;
 $xml->load('example.xml');

 $xpath = new DOMXpath($xml);

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

 ?>

 <?php
 if (isset($_POST['submit']))
 {
$asstatus->nodeValue = $_POST['asstatusform'];
htmlentities($xml->save('example.xml'));
 }

 ?>

<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>
</select></span>
<br>
<input name="submit" type="submit" value="Save" />
</form>

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")."/".
              $trail->getAttribute("status").PHP_EOL;
    }
    

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