简体   繁体   中英

Grab xml attribute with xpath and php

I have the following

    $records = $xml->xpath("//Affiliates/Affiliate"); 
    foreach ($records as $record){
     $Clicks = $record->StatRow->Statistics->Clicks;
     $Id = $record->Affiliate['Id'];
    }

All of this works, but I can't figure out how to grab the node attribute "id" from the affiliate node.

    $records = $xml->xpath("//Affiliates"); 
    foreach ($records as $record){
     $Clicks = $record->Affiliate->StatRow->Statistics->Clicks;
     $Id = $record->Affiliate['Id'];
    }

This works as well but then the loop breaks and I only return a single record, what am I missing?

Try this:

Suppose your xml is this:

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

Your PHP code here:

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

It prints:

Array
(
    [0] => Array
        (
            [id] => 1
            [clicks] => click1
        )

    [1] => Array
        (
            [id] => 2
            [clicks] => click2
        )

)

Hope it helps..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM