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 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线