xpath找不到任何东西-PHP


xpath finds nothing - PHP

简介

我有一些SQL代码。我在php中的while循环中逐个代码,并在XML提要中搜索这些代码。

程序代码

我有以下程序代码

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

问题

有些代码可能不在SQL中。所以我得到了这个错误消息:

Undefined offset: 0 in

如果您在XML中找到它,$x_Id=$x_search[0]->attributes((->Id;?

我已经试过了:

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

示例XML:

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

$sort:示例

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

感谢

SimpleXMLElement::xpath()始终返回一个SimpleXMLElement对象数组。如果没有任何匹配项,则数组为空。如果表达式无效(编程错误(,则结果可能等于false。因此CCD_ 4或CCD_。false是一个空值,并且一个空数组等于false。如果表达式的结果是至少包含单个元素的数组,则这两个条件都将仅为true

$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 />";
}

输出:https://eval.in/406640

0001KC - 12860<BR />

$sort的大多数示例值看起来像Id属性值。第二个是示例XML中的Id属性值。

如果你想匹配Id属性,Xpath表达式应该是:

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

甚至可以同时匹配两个属性:

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

这是XML的一个示例。A我写的有可能,有些代码不在SQL中。所以这就是为什么我需要解决这个问题。只有在XML中找到这种类型时,才能给我写一个echo之类的东西。

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

进入不变$sort 的代码列表的开头

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