“At sign” @ in SimpleXML object?

前端 未结 4 2003
臣服心动
臣服心动 2020-12-04 01:56

This is the output of print_r() run on a typical SimpleXMLElement object:

SimpleXMLElement Object
(
    [@attributes] => Array
        (

            


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 02:03

    I am working with an HTTP API that gives out only XML formatted data. So first I loaded it into SimpleXML and was also puzzled by the @attributes issue.. how do I get at the precious data it contains? print_r() confused me.

    My solution was to create an array and an iterator variable at 0. Loop through a SimpleXML object with foreach and get at the data with the attribues() method and load it into my created array. Iterate before foreach loop ends.

    So print_r() went from showing this:

    SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [ID] => 1
                [First] => John
                [Last] => Smith
            )
    )
    

    To a much more usable normal array. Which is great because I wanted the option to quickly convert array into json if needed.

    My solution in code:

    $obj = simplexml_load_string($apiXmlData);
    $fugly = $obj->Deeply->Nested->XML->Data->Names;
    $people = array();
    $i = 0;
    foreach($fugly as $val)
    {
      $people[$i]['id'] += $val->attributes()->ID;
      $people[$i]['first'] = "". $val->attributes()->First;
      $people[$i]['last'] = "". $val->attributes()->Last;
      $i++;
    }
    

    Quick note would be PHP's settype() function is weird/buggy, so I added the + to make sure ID is an integer and added the quotes to make sure the name is string. If there isn't a variable conversion of some kind, you're going to be loading SimpleXML objects into the array you created.

    Final result of print_r():

    Array
    (
       [0] => Array
        (
            [id] => 1
            [first] => John
            [last] => Smith
        )
    
       [1] => Array
        (
            [id] => 2
            [first] => Jane
            [last] => Doe
        )
    )
    

提交回复
热议问题