douruhu4282 2019-06-11 17:26
浏览 176
已采纳

在PHP中使用XPath替换XML属性

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!

  • 写回答

1条回答 默认 最新

  • dragon8899 2019-06-11 20:16
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器