PHP DOMDocument 获取标签的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1597746/
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 03:14:11  来源:igfitidea点击:

PHP DOMDocument getting Attribute of Tag

phpparsingdomdomdocumentxml-namespaces

提问by David Willis

Hello I have an api response in xml format with a series of items such as this:

您好,我有一个 xml 格式的 api 响应,其中包含一系列项目,例如:

<item>
<title>blah balh</title>
<pubDate>Tue, 20 Oct 2009 </pubDate>
<media:file  date="today" data="example text string"/>
</item>

I want to use DOMDocument to get the attribute "data" from the tag "media:file". My attempt below doesn't work:

我想使用 DOMDocument 从标签“media:file”中获取属性“data”。我在下面的尝试不起作用:

$xmldoc = new DOMDocument();
$xmldoc->load('api response address');
foreach ($xmldoc->getElementsByTagName('item') as $feeditem) {
$nodes = $feeditem->getElementsByTagName('media:file');
$linkthumb = $nodes->item(0)->getAttribute('data');
}

What am I doing wrong? Please help.

我究竟做错了什么?请帮忙。

EDIT: I can't leave comments for some reason Mark. I get the error

编辑:由于某种原因,我不能发表评论马克。我收到错误

 Call to a member function getAttribute() on a non-object

when I run my code. I have also tried

当我运行我的代码时。我也试过

$nodes = $feeditem->getElementsByTagNameNS('uri','file');
$linkthumb = $nodes->item(0)->getAttribute('data');

where uri is the uri relating to the media name space(NS) but again the same problem.

其中uri是与媒体名称空间(NS)相关的uri,但同样的问题。

Note that the media element is of the form not I think this is part of the problem, as I generally have no issue parsing for attibutes.

请注意,媒体元素的形式不是我认为这是问题的一部分,因为我通常没有解析属性的问题。

回答by Mark

The example you provided should not generate an error. I tested it and $linkthumb contained the string "example text string" as expected

您提供的示例不应产生错误。我对其进行了测试,$linkthumb 按预期包含字符串“示例文本字符串”

Ensure the medianamespace is defined in the returned XML otherwise DOMDocument will error out.

确保在返回的 XML 中定义了媒体命名空间,否则 DOMDocument 将出错。

If you are getting a specific error, please edit your post to include it

如果您遇到特定错误,请编辑您的帖子以包含它

Edit:

编辑:

Try the following code:

试试下面的代码:

$xmldoc = new DOMDocument();
$xmldoc->load('api response address');
foreach ($xmldoc->getElementsByTagName('item') as $feeditem) {
    $nodes = $feeditem->getElementsByTagName('file');
    $linkthumb = $nodes->item(0)->getAttribute('data');
    echo $linkthumb;
}

You may also want to look at SimpleXMLand Xpathas it makes reading XML much easier than DOMDocument.

您可能还想查看SimpleXMLXpath,因为它使读取 XML 比 DOMDocument 容易得多。

回答by Leprechaun

Alternatively,

或者,

$DOMNode -> attributes -> getNamedItem( 'MyAttribute' ) -> value;