[英]Grab xml attribute with xpath and php
我有以下
$records = $xml->xpath("//Affiliates/Affiliate");
foreach ($records as $record){
$Clicks = $record->StatRow->Statistics->Clicks;
$Id = $record->Affiliate['Id'];
}
所有这些都有效,但是我不知道如何从关联节点获取节点属性“ id”。
$records = $xml->xpath("//Affiliates");
foreach ($records as $record){
$Clicks = $record->Affiliate->StatRow->Statistics->Clicks;
$Id = $record->Affiliate['Id'];
}
这样也可以,但是循环中断,我只返回一条记录,我想念的是什么?
尝试这个:
假设您的xml是这样的:
<!-- SAVE THIS FILE AS affiliate.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<Affiliates>
<Affiliate Id="1">
<StatRow>
<Statistics>
<Clicks>click1</Clicks>
</Statistics>
</StatRow>
</Affiliate>
<Affiliate Id="2">
<StatRow>
<Statistics>
<Clicks>click2</Clicks>
</Statistics>
</StatRow>
</Affiliate>
</Affiliates>
您的PHP代码在这里:
<?php
// load the xml file
$file = simplexml_load_file( 'affiliate.xml' );
$records = $file->xpath("//Affiliates/Affiliate");
$data = array();
foreach ($records as $key => $record) {
$data[ $key ][ 'id' ] = ( int ) $record['Id'];
$data[ $key ][ 'clicks' ] = ( string ) $record->StatRow->Statistics->Clicks;
}
// check data
print_r($data);
?>
它打印:
Array
(
[0] => Array
(
[id] => 1
[clicks] => click1
)
[1] => Array
(
[id] => 2
[clicks] => click2
)
)
希望能帮助到你..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.