我需要从xpath查询返回多个值,如下面的编码所示。我有一个XML文件和简单的值。我将使用PHP中的XPath从XML获取帐户名和电子邮件地址值,并且需要将它们作为逗号分隔值进行回显。因此,使用下面的代码,结果将是:
Company A,mail@company-a.com
Company B,mail@company-b.com
这是我的代码:
<?php
$XMLfile = "test.xml";
$a = 'result/Accounts/row/FL[@val="Account Name"]';
$e = 'result/Accounts/row/FL[@val="E-mail Address"]';
$xml = simplexml_load_file($XMLfile);
$result = $xml->xpath($a);
$result2 = $xml->xpath($e);
foreach ($result as $le_result)
echo $le_result."<br>";
?>
和'test.xml'包含:
<?xml version="1.0" encoding="UTF-8"?>
<result>
<Accounts>
<row>
<FL val="Account Name">
Company A
</FL>
<FL val="E-mail Address">
mail@company-a.com
</FL>
</row>
<row>
<FL val="Account Name">
Company B
</FL>
<FL val="E-mail Address">
mail@company-b.com
</FL>
</row>
</Accounts>
</result>
答案 0 :(得分:0)
查询<row>
元素可能更容易,
然后通过$row->FL[0]
和电子邮件$row->FL[1]
$a = '//result/Accounts/row';
foreach ($xml->xpath($a) as $row){
echo sprintf(
"%s, %s<br>",
$row->FL[0], //name
$row->FL[1] //email
);
}