简体   繁体   English

用xpath过滤php simple_xml加载结果

[英]Filter php simple_xml load results with xpath

I need a little help to figure out XPath search inside XML output simple_xml_load in PHP. 我需要一点帮助来弄清楚PHP中XML输出simple_xml_load中的XPath搜索。 I have this XML: 我有这个XML:

<PRODUCTS>
  <PRODUCT>
    <CODE>5009444</CODE>
    <NAME>Prova</NAME>
    <IMG>prova.jpg</IMG>
  </PRODUCT>
  ....
  ....
</PRODUCTS>

I want to filter and iterate through this data to find and return all occurrences with a variable code. 我想过滤并遍历此数据以查找并返回带有可变代码的所有事件。 I used this syntax but didn't work 我使用了这种语法,但是没有用

$id = 1;
$struct = \App\Models\Structures::where('id', $id)->first();
$url = 'http://demo.villaggissimi.it/public/xml/CMP_' . $struct->operators->pk .'.xml';
$xc = simplexml_load_file($url) or die("Non sono stati trovati risultati");
$xml2 = $xc->xpath("/PRODUCTS/PRODUCT[CODE='$struct->code']");
return response()->json($xml2);

The result of the Xpath Expression is a node list, SimpleXMLElement:xpath() only supports that kind of result, it will always return an array of SimpleXMLElement objects (for a valid Xpath expression). Xpath表达式的结果是一个节点列表,SimpleXMLElement:xpath()仅支持这种结果,它将始终返回一个SimpleXMLElement对象数组(用于有效的Xpath表达式)。

So you still have to use foreach()/if() to avoid an error message if no element has been found. 因此,如果未找到任何元素,您仍然必须使用foreach()/if()以避免出现错误消息。

You can however limit the result to a list with only a single node. 但是,您可以将结果限制为仅包含一个节点的列表。

foreach ($xc->xpath("/PRODUCTS/PRODUCT[CODE='$struct->code'][1]") as $productNode) {
  return response()->json($productNode);
}
return FALSE;

$productNodes = $xc->xpath("/PRODUCTS/PRODUCT[CODE='$struct->code'][1]");
if (count($productNodes) > 0) {
  return response()->json($productNodes[0]);
}
return FALSE;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM