当我的子值与“id22”
匹配时,我想获取父数据<servers>
<someservers>
<owner>id0</owner>
<serverCode>fefwewf</serverCode>
<address>345345</address>
<authCertHash>efref</authCertHash>
<authCertHash>erferf=</authCertHash>
<client>id1</client>
<client>id22</client>
</someservers>
<someservers>
<owner>id33</owner>
<serverCode>f</sewewefrverCode>
<address>234234234</address>
<authCertHash>sdfs</authCertHash>
<client>id27</client>
</someservers>
</server>
目前我正在尝试如下:
$server = $xml -> xpath('//someservers//client='id22');
echo $server->address;
但它不起作用,我收到错误:
Trying to get property of non-object in...
我希望得到输出:
345345
答案 0 :(得分:1)
SimpleXMLElement::xpath()
仅支持返回节点列表的Xpath表达式,因此可以将它们转换为SimpleXMLElement
个实例的数组。
@andersson已经解释过,表达式只返回指定客户端元素的存在。你需要使用一个条件。这将返回一个数组,其中包含匹配的SimpleXMLElement
个对象作为元素。
$servers = new SimpleXMLElement($xml);
$server = $servers->xpath('//someservers[client="id22"]')[0];
echo $server->address;
输出:
345345
DOMXpath::evaluate()
能够直接返回标量值:
$document = new DOMDocument();
$document->loadXml($xml);
$xpath= new DOMXpath($document);
echo $xpath->evaluate('string(//someservers[client="id22"]/address)');
答案 1 :(得分:0)
您的XPath
//someservers//client='id22
打算返回布尔值true
/ false
,但不返回元素或其文本内容
尝试使用以下XPath
表达式
//someservers[client='id22']/address/text()
应该返回所需的"345345"