1

I have an XML like the one below, I am trying to do an xpath query and parse it with simplexml. The XML is a CURL response and is stored in a $response variable. I need to look the Code attribute inside the <Item> and select the parent <Product> to parse it.

$response:

<Items>
 <Product>
  <Item Code="123">
  </Item>
  <Price>170
  </Price>
 </Product>
 <Product>
  <Item Code="456">
  </Item>
  <Price>150
  </Price>
 </Product>
</Items>

This is what I am doing:

$xml = simplexml_import_dom($response); 

function loadNode($code){
    global $xml;
    $scode = $xml->xpath('//Item[contains(@Code,"' . $code . '")]/..');
    echo $scode->Items->Product->Price;
}

loadNode("123");

This is the Notice I get:

Notice: Trying to get property of non-object

4

1 回答 1

1

几点观察:

  • xpath()方法返回一个对象数组SimpleXMLElement 而不是单个SimpleXMLElement. (是的,即使元素只能有一个父元素,您仍然必须将其作为数组的第一个成员 ( [0])。
  • $scode->Items->Product->Price应该改为 just $scode->Price

对您的 PHP 代码的这些修改:

<?php
$response = <<<XML
<Items>
  <Product>
    <Item Code="123">
    </Item>
    <Price>170
    </Price>
  </Product>
  <Product>
    <Item Code="456">
    </Item>
    <Price>150
    </Price>
  </Product>
</Items>
XML;

$xml = simplexml_load_string($response);

function loadNode($code) {
  global $xml;
  $scode = $xml->xpath('//Item[contains(@Code,' . $code . ')]/..')[0];
  echo $scode->Price;
}

loadNode("123");
?>

运行时将产生此输出:

170

正如预期的那样。

于 2013-11-01T03:26:03.143 回答