简体   繁体   中英

Replacing XML Attribute using XPath in PHP

I have an XML file that looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<facilities>
    <areas>
        <area name="Rocket">
            <trails>
                <trail name="This Skiway" status="CLOSED" difficulty="novice"/>
            </trails>
        </area>
    </areas>
</facilities>

I'm trying to make the attributes show up in a form so that I can replace them. I've had success with getElementsbyTagName and replacing content inside a tag, but when I introduce XPath and try to replace the attributes it just doesn't work.

The code I'm using is this:

<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('examples.xml');

 $xpath = new DOMXpath($xml);

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

 $xpath->replaceChild($name, $name);
 $xpath->replaceChild($status, $status);
 ?>

 <?php
 if (isset($_POST['submit']))
 {
$name->nodeValue = $_POST['namanya'];
$status->nodeValue = $_POST['statusnya'];
htmlentities($xml->save('examples.xml'));

 }

 ?>

<form method="POST" action=''>
  name <input type="text-name" value="<?php echo $name->nodeValue  ?>" name="namanya" />

<span><label for='statusnya'>status </label>
<select name="statusnya" id="statusnya">
<option selected value="<?php echo $status->nodeValue  ?>"><?php echo $status->nodeValue  ?></option>
<option value="OPEN">OPEN</option>
<option value="CLOSED">CLOSED</option>
<option value="RACING CLOSURE">RACING CLOSURE</option>
</select></span>

<input name="submit" type="submit" />
</form>

Not sure what I'm doing wrong here but I think my xpath query is bad somehow. Many thanks!

The answer as Nigel Ren suggested was just to remove these two lines, as they no longer apply:

 $xpath->replaceChild($name, $name);
 $xpath->replaceChild($status, $status);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM