doulin4844 2015-07-27 09:30
浏览 52
已采纳

xpath找不到任何东西 - PHP

Introduction

I have some codes in SQL. I go code by code in while loop in php and search these codes in XML feed.

Programm code

I have the following programm code

$x_search = $xml->xpath("//Item[@Sort='$sort']");
if(!$x_search){
    $x_Id = $x_search[0]->attributes()->Id;
    echo $sort." - ".$x_Id."<BR />";
}

Problem

It is possible, that some code is not in SQL. So I get this error message:

Undefined offset: 0 in

How to do something like if you find it in XML, $x_Id = $x_search[0]->attributes()->Id;?

I have tried already:

  1. $x_search = $xml->xpath("//*[@Sort='$sort']");
  2. if(!empty($x_search)){
  3. if(isset($x_search)){

Example XML:

<?xml version="1.0" encoding="utf-8"?>
<Root>
  <Item Id="12860" IdP="-2147483648" Sort="0001KC" Name="Computers">
    <StoItem />
  </Item>
</Root>

Examples for $sort:

00004M
12860
12859
12859
12861
12861
12862
12862
12863
12863
12864

Thank you

  • 写回答

2条回答 默认 最新

  • dongxie2749 2015-07-27 10:29
    关注

    SimpleXMLElement::xpath() always returns an array of SimpleXMLElement objects. The array is empty, if nothing is matched. The result can equal false, if the expression is invalid (programming error). So if (!empty($x_search)) ... or if ($x_search) ... can be used as condition to check the result. false is an empty value and an empty array equals false. Both conditions will only be true if the result from the expression is an array with at least a single element.

    $xmlString = <<<'XML'
    <?xml version="1.0" encoding="utf-8"?>
    <Root>
      <Item Id="12860" IdP="-2147483648" Sort="0001KC" Name="Computers">
        <StoItem />
      </Item>
    </Root>
    XML;
    
    $xml = new SimpleXmlElement($xmlString);
    $sort = '0001KC';
    
    $x_search = $xml->xpath("//Item[@Sort='$sort']");
    if (!empty($x_search)) {
        $x_Id = $x_search[0]->attributes()->Id;
        echo $sort." - ".$x_Id."<BR />";
    }
    

    Output: https://eval.in/406640

    0001KC - 12860<BR />
    

    Most of your example values for $sort look like Id attribute values. The second one, is the Id attribute value in the example XML.

    If you want to match the Id attribute, the Xpath expression would be:

    //Item[@Id='$sort']

    It is even possible to match both attributes:

    //Item[@Id='$sort' or @Sort='$sort']

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件