Search code examples
xmlsimplexml

Using SimpleXML to read attributes


I am still trying to get the hang of PHP and XML. I have a XML that I am going to truncate to save space. I would like to get the dimension name attribute display-name value from each of the records. I also have to get the servermanager status value from each of the records as well.

I was using:

$completeurl = "http://website/data.xml";
$xml = simplexml_load_file($completeurl);
$xml->dimension;

for ($i = 0; $i < 2; $i++) {
    $servername = $dimensions[$i]->attributes()->display-name;
    $status = $dimensions[$i]->servermanager;
};

However, I am getting:

Fatal error: Call to a member function attributes() on a non-object in the lines I am trying to assign variables.

I am removing all the extra data between the dimension that I don't want to parse. The truncated XML is:

<?xml version="1.0"?>
<aostats version="0.6" timestamp="2013-02-13 21:16:01 UTC">
    <dimension name="d1" display-name="Atlantean" loadmax="2" locked="0" players="100%">
        <servermanager status="1"/>
        <clientmanager status="0"/>
        <chatserver status="1"/>
    </dimension>
    <dimension name="d2" display-name="Rimor" loadmax="2" locked="0" players="100%">
        <servermanager status="1"/>
        <clientmanager status="0"/>
        <chatserver status="1"/>
    </dimension>
    <dimension name="dt" display-name="Test" loadmax="2" locked="0" players="100%">
        <servermanager status="1"/>
        <clientmanager status="0"/>
    </dimension>
</aostats>

Solution

  • I found the answer myself by experimenting:

    $completeurl = = "http://website/data.xml";
    $xml = simplexml_load_file($completeurl);
    $dimensions  = $xml->dimension;
    for ($i = 0; $i < 3; $i++) {
    $servername = $dimensions[$i]["display-name"];
    $status = $dimensions[$i]->servermanager["status"];
    }