php SimpleXML:选择具有特定属性值的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/992450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:34:58  来源:igfitidea点击:

SimpleXML: Selecting Elements Which Have A Certain Attribute Value

phpxmlxpathsimplexmlnetflix

提问by dimo414

In an XML document, I have elements which share the same name, but the value of an attribute defines what type of data it is, and I want to select all of those elements which have a certain value from the document. Do I need to use XPath (and if so, could you suggest the right syntax) or is there a more elegant solution?

在 XML 文档中,我有共享相同名称的元素,但属性的值定义了它是什么类型的数据,我想从文档中选择所有具有特定值的元素。我是否需要使用 XPath(如果需要,您能否建议正确的语法)还是有更优雅的解决方案?

Here's some example XML:

这是一些示例 XML:

<object>
  <data type="me">myname</data>
  <data type="you">yourname</data>
  <data type="me">myothername</data>
</object>

And I want to select the contents of all <data>tags children of <object>who's type is me.

我想选择who's type is的所有<data>标签的内容。<object>me

PS - I'm trying to interface with the Netflix API using PHP - this shouldn't matter for my question, but if you want to suggest a good/better way to do so, I'm all ears.

PS - 我正在尝试使用 PHP 与 Netflix API 进行交互 - 这对我的问题来说无关紧要,但是如果您想提出一个好的/更好的方法,我会全力以赴。

回答by Gumbo

Try this XPath:

试试这个 XPath:

/object/data[@type="me"]

So:

所以:

$myDataObjects = $simplexml->xpath('/object/data[@type="me"]');

And if objectis not the root of your document, use //object/data[@type="me"]instead.

如果object不是您文档的根目录,请//object/data[@type="me"]改用。

回答by willbradley

I just made a function to do this for me; it only grabs the first result though. Your mileage may vary.

我刚刚做了一个功能来为我做这件事;不过,它只获取第一个结果。你的旅费可能会改变。

function query_attribute($xmlNode, $attr_name, $attr_value) {
  foreach($xmlNode as $node) { 
    switch($node[$attr_name]) {
      case $attr_value:
        return $node;
    }
  }
}

Usage:

用法:

echo query_attribute($MySimpleXmlNode->Customer, "type", "human")->Name;

(For the XML below)

(对于下面的 XML)

<Root><Customer type="human"><Name>Sam Jones</name></Customer></Root>