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条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大