使用xpath和php获取xml属性


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
        )
)

希望能有所帮助。。