doumu4916 2014-10-10 04:28
浏览 195

在XML中提取一个值[重复]

This question already has an answer here:

I am new to processing and reading XML strings in PHP

I have XML like this

<sports-metadata>
  <sports-content-codes>
    <sports-content-code code-type="sport" code-key="15027000" code-name="Golf"/>
    <sports-content-code code-type="league" code-key="l.pga.com" code-name="Professional Golf Association"/>
    <sports-content-code code-type="season-type" code-key="regular"/>
    <sports-content-code code-type="season" code-key="2015"/>
    <sports-content-code code-type="priority" code-key="normal"/>
  </sports-content-codes>
</sports-metadata>

I have read in the XML via a $xml=simplexml_load_file()

I can get to this XML section via $xml->{'sports-content-codes'}->{'sports-content-code'}

In sports-content-code

I want to access/retrieve the code-key value where code-type="season"

How can I do this in PHP?

Thank you all.

-- Ed

</div>
  • 写回答

2条回答 默认 最新

  • duanshan3331 2014-10-10 04:34
    关注

    Usually you use ->attributes() method to get those attributes:

    foreach($xml->{'sports-content-codes'}->{'sports-content-code'} as $content_code) {
        $attr = $content_code->attributes();
        $code_type = (string) $attr->{'code-type'};
        echo $code_type;
    }
    

    Sample Output

    评论

报告相同问题?