[英]Get XML element by tag name
var_dump($object)
outputs the following result: var_dump($object)
输出以下结果:
object(stdClass)#9 (5) {
["data"]=> object(stdClass)#8 {
["validFiling"]=> object(stdClass)#7 {
["indicators"]=> string(6) "MODE_S"
}
["plan"]=> object(stdClass)#6 {
["id"]=> string(10) "xxx"
}
}
}
In this data structure I need to access the content of the field id
. 在此数据结构中,我需要访问字段
id
的内容。 I do this in the following way: 我通过以下方式执行此操作:
try
{
$object = $client->getPlan($p);
var_dump($object);
}
catch (Exception $e) {
print $e->getMessage();
}
$line = $client->getLastResponse();
$doc = new DOMDocument();
$doc->loadXML($line);
$data = $doc->getElementsByTagName('data');
$fp = $data->getElementsByTagName('plan');
$id = $fp->getElementsByTagName('id');
$fId = $id->item(0)->nodeValue;
And the error is (at the line $fp = $data->getElementsByTagName('plan')
): 错误是(在
$fp = $data->getElementsByTagName('plan')
):
Call to undefined method DOMNodeList::getElementsByTagName()
How to solve this issue? 如何解决这个问题?
The error occurs because $data
is a DOMNodeList
which doesn't have the getElementsByTagName()
method. 发生错误是因为
$data
是一个没有getElementsByTagName()
方法的DOMNodeList
。 You have the same problem with the $fp
variable. $fp
变量也有相同的问题。 If you want to access the first data
element found, then change to: 如果要访问找到的第一个
data
元素,请更改为:
$data = $doc->getElementsByTagName('data')->item(0);
$fp = $data->getElementsByTagName('plan')->item(0);
$id = $fp->getElementsByTagName('id');
Or if you want to iterate of the data
elements and apply the processing to each: 或者,如果您要迭代
data
元素并将处理应用于每个元素:
$dataList = $doc->getElementsByTagName('data');
foreach($dataList as $data)
{
$fp = $data->getElementsByTagName('plan')->item(0);
$id = $fp->getElementsByTagName('id');
$fId = $id->item(0)->nodeValue;
}
The above works because its calling getElementsByTagName()
on the node itself not the list. 上面的方法是有效的,因为它在节点本身而不是列表上调用
getElementsByTagName()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.