我正在寻找一种使用 php 从 xml 文件中获取特殊类型子项的方法。xml:
<notify type="post" name="Max" />
我想从那里抢到名字。我的代码:`$sender =
$sender = $node->getChild('notify');
$sender = $sender->getChild('name');
$sender = $sender->getData();
但正如我所料,它不是那样工作的。提前感谢您的帮助
您可以使用xpath表达式来完成工作。它类似于 XML 的 SQL 查询。
$results = $xml->xpath("//notify[@type='post']/@name");
假设 XML in $xml,表达式如下
select all notify nodes,
where their type-attribute is post,
give back the name-attribute.
$results将是一个数组,我的代码示例是为simplexml. 不过,您可以使用相同xpath-expression的方法DOM。
这是完整的代码:
$x = <<<XML
<root>
<notify type="post" name="Max" />
<notify type="get" name="Lisa" />
<notify type="post" name="William" />
</root>
XML;
$xml = simplexml_load_string($x);
$results = $xml->xpath("//notify[@type='post']/@name");
foreach ($results as $result) echo $result . "<br />";
输出:
Max
William