在PHP中使用XPath替换XML属性

时间:2019-06-11 17:26:12

标签: php xml xpath

我有一个看起来像这样的XML文件:

<?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>

我正在尝试使属性以一种形式显示,以便我可以替换它们。我已经成功使用了getElementsbyTagName并替换了标签中的内容,但是当我引入XPath并尝试替换属性时,它只是行不通。

我正在使用的代码是这样:

<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>

不知道我在做什么错,但我认为我的xpath查询不好。非常感谢!

1 个答案:

答案 0 :(得分:0)

Nigel Ren建议的答案只是删除这两行,因为它们不再适用:

SECOND TEST