PHP get values from SimpleXMLElement array

前端 未结 4 1746
天命终不由人
天命终不由人 2020-11-29 10:48

I have this:

  [1]=>
object(SimpleXMLElement)#6 (1) {
  [\"@attributes\"]=>
  array(14) {
    [\"name\"]=>
    string(5) \"MySQL\"
    [\"acknowledg         


        
相关标签:
4条回答
  • 2020-11-29 11:17

    Kind of messy, but I used this successfully

    foreach($xml->data->children() as $child) {
    //var_dump($child);
        foreach ($child->attributes() as $a => $b) {
         echo $a . '=' . $b . '<br />';
        }
    }
    

    Not sure why, but the OpsView API returns a two-dimensional array instead of just having one value per XML node :(

    echo $child['name'];
    

    works and is much more elegant, thank you.

    0 讨论(0)
  • 2020-11-29 11:18

    While you can do:

    echo $child['name'];
    

    to see the value, you should note that $child['name'] is an object, not a string. Echoing it casts it to a string, so it works in that situation. But if you're storing it somewhere, it's better to cast it to a string yourself:

    $name = (string) $child['name'];
    
    0 讨论(0)
  • 2020-11-29 11:20

    I had a similar problem, I needed to get the string out of my SimpleXMLElement, I couldn't find the name to call it. Found the solution, by using (string) to get the string text:

    foreach ($lines as $line) {
        array_push($result, new line(**(string)**$line));
    }
    
    array
      0 => 
        object(line)[190]
          private '_line' => 
            object(SimpleXMLElement)[128]
              public '@attributes' => 
                array
                  ...
              string ' ' (length=1)
      1 => 
        object(line)[191]
          private '_line' => 
            object(SimpleXMLElement)[131]
              public '@attributes' => 
                array
                  ...
              string ' ' (length=1)
      2 => 
        object(line)[192]
          private '_line' => 
            object(SimpleXMLElement)[132]
              public '@attributes' => 
                array
                  ...
              string ' ~54**** I N V O I C E ****' (length=27)
    
    0 讨论(0)
  • 2020-11-29 11:32

    With SimpleXML, you can get :

    • sub-elements, using object notation : $element->subElement
    • and attributes, using array notation : $element['attribute']


    So, here, I'd say you'd have to use :

    echo $child['name'];
    


    As a reference, and for a couple of examples, see the Basic usage section of simplexml's manual.

    Example #6 should be the interesting one, about attributes.

    0 讨论(0)
提交回复
热议问题