-2

Possible Duplicate:
SimpleXML get element content based on attribute value

I've looked through several related topics but can't find an answer.

How can I print, for example the value of curr for the USD currency?

            <?xml version="1.0"?>
            <currencies>
                <currency id="AUD">
                        <curr>Australian dollar</curr>
                        <loc>Australia, Australian Antarctic Territory, Christmas Island, Cocos (Keeling) Islands, Heard and McDonald Islands, Kiribati, Nauru, Norfolk Island, Tuvalu</loc>
                </currency>
                <currency id="USD">
                        <curr>United States Dollar</curr>
                        <loc>American Samoa, British Indian Ocean Territory, Caribbean Netherlands, Ecuador, El Salvador, Guam, Haiti, Marshall Islands, Micronesia, Northern Mariana Islands, Palau, Panama, Puerto Rico, Timor-Leste, Turks and Caicos Islands, United States, U.S. Virgin Islands, Barbados (as well as Barbados Dollar), Bermuda (as well as Bermudian Dollar), Zimbabwe</loc>
                </currency>
            </currencies>

I can print what I want specifically by doing this:

    foreach($xml as $currency) {
        echo $currency[0]->curr;
    }   

But it's not quite what I'm after. Also - is my XML markup okay for what I'm trying to achieve or could this be achieved an easier way?

Community
  • 1
  • 1
tctc91
  • 1,343
  • 2
  • 21
  • 41

2 Answers2

2

Do it with the XPath syntax: http://php.net/manual/simplexmlelement.xpath.php

$string = '<?xml version="1.0"?>
            <currencies>
                <currency id="AUD">
                        <curr>Australian dollar</curr>
                        <loc>Australia, Australian Antarctic Territory, Christmas Island, Cocos (Keeling) Islands, Heard and McDonald Islands, Kiribati, Nauru, Norfolk Island, Tuvalu</loc>
                </currency>
                <currency id="USD">
                        <curr>United States Dollar</curr>
                        <loc>American Samoa, British Indian Ocean Territory, Caribbean Netherlands, Ecuador, El Salvador, Guam, Haiti, Marshall Islands, Micronesia, Northern Mariana Islands, Palau, Panama, Puerto Rico, Timor-Leste, Turks and Caicos Islands, United States, U.S. Virgin Islands, Barbados (as well as Barbados Dollar), Bermuda (as well as Bermudian Dollar), Zimbabwe</loc>
                </currency>
            </currencies>';

$xml = new SimpleXMLElement($string);
var_dump($xml->xpath('//currency[@id="USD"]');
powtac
  • 40,542
  • 28
  • 115
  • 170
0

Try

$data = simplexml_load_string($xml);
foreach($data->currencies as $currency) {
    // $currency->curr.. etc
]
Gabriel Santos
  • 4,934
  • 2
  • 43
  • 74