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

在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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵