请忽略XML数据的语义。我想扫描整个xml文件,只抓取banana值并将它们存储为PHP中的数组。
<?xml version="1.0" encoding="UTF-8" ?>
<data>
<fruits>
<fruit id="1" >
<aisle1>
<apple>aa</apple>
<banana>ab</banana>
<cherry>ac</cherry>
<damson>ad</damson>
</aisle1>
<aisle2>
<apple>none</apple>
<banana>3708650582321691833</banana>
<cherry>none</cherry>
<damson>none</damson>
</aisle2>
<aisle3>
<apple>none</apple>
<banana>3708650582321691833</banana>
<cherry>none</cherry>
<damson>none</damson>
</aisle3>
</fruit>
<fruit id="2" >
<aisle1>
<apple>none</apple>
<banana>3708650582321691833</banana>
<cherry>none</cherry>
<damson>none</damson>
</aisle1>
<aisle2>
<apple>none</apple>
<banana>3708650582321691833</banana>
<cherry>none</cherry>
<damson>none</damson>
</aisle2>
<aisle3>
<apple>none</apple>
<banana>3708650582321691833</banana>
<cherry>none</cherry>
<damson>none</damson>
</aisle3>
</fruit>
</fruits>
xPath可以让我这样做吗?我目前有:
$xml->xpath("//fruits//fruit//bananas->text()";
感谢。
答案 0 :(得分:1)
如果您只是对该特定节点感兴趣,只需直接查询它:
$just_bunch_of_bananas = array();
$bananas = $xml->xpath('//banana'); // directly get it
foreach($bananas as $banana) { // loop each banana node :)
echo $banana . '<br/>';
$just_bunch_of_bananas[] = (string) $banana;
}
按行:
$rows = array();
$fruits = $xml->xpath('//fruit');
foreach($fruits as $fruit) {
foreach($fruit as $row => $aisles) {
$rows[] = array('apple' => (string )$aisles->apple, 'banana' => (string )$aisles->banana);
}
}
echo '<pre>';
print_r($rows);