dragonmeng2002 2014-01-21 02:01
浏览 50
已采纳

PHP SimpleXML XPath查询

I have a function which is trying to get text from XML using XPath query.The function reads:

function getInterviewText($id)  {
    $sxe = simplexml_load_file("./interview2.xml");
    foreach($sxe->xpath('//interview') as $item) {
        $row = simplexml_load_string($item->asXML());
        $v = $row->xpath('//interview-id[.="$id"]');
        if($v[0]) {
            echo '<interview-text>'.$item->INTERVIEW-TEXT.'</interview-text>' 
        }
    }
}

The XML File reads:

<?xml version="1.0"?>
<ROOT>
    <interview>
        <interview-id>1</interview-id>
        <INTERVIEW-TEXT>                                
            Test1
        </INTERVIEW-TEXT>
    </interview>
    <interview>
        <interview-id>2</interview-id>
        <INTERVIEW-TEXT>                              
            Test2          
        </INTERVIEW-TEXT>
    </interview>
</ROOT>

However, the function is not returning anything, when I am trying to call it with id=1 or 2. Any help is greatly appreciated.

Thanks

  • 写回答

1条回答 默认 最新

  • dsj83686 2014-01-21 02:07
    关注

    The problem is here:

    $v = $row->xpath('//interview-id[.="$id"]');
    

    $id is not being expanded because you are within a single-quoted string. Try one of the following instead:

    $v = $row->xpath('//interview-id[.="' . $id . '"]');
    // Or
    $v = $row->xpath("//interview-id[.=\"{$id}\"]");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)