如何在php中使用属性遍历对象值

I am having my data in xml. And I want to traverse it. When I print var_dump($video_xml->playlist->video->labels->label) the output is

object(SimpleXMLElement)#41 (4) {
  ["@attributes"]=>
  array(11) {
    ["id"]=>
    string(1) "0"
    ["start"]=>
    string(1) "0"
    ["end"]=>
    string(17) "8.639527777777777"
    ["pos"]=>
    string(12) "124,66,95,45"
    ["marker"]=>
    string(5) "false"
    ["href"]=>
    string(0) ""
    ["bold"]=>
    string(5) "false"
    ["italic"]=>
    string(5) "false"
    ["color"]=>
    string(17) "rgb(62, 201, 106)"
    ["face"]=>
    string(7) "Verdana"
    ["size"]=>
    string(2) "24"
  }
  [0]=>
  string(8) "Label1fg"
  [1]=>
  string(6) "Label0"
  [2]=>
  string(6) "Label0"
}

however when I print each object in a foreach loop it gives

object(SimpleXMLElement)#56 (1) {
  ["@attributes"]=>
  array(11) {
    ["id"]=>
    string(1) "0"
    ["start"]=>
    string(1) "0"
    ["end"]=>
    string(17) "8.639527777777777"
    ["pos"]=>
    string(12) "124,66,95,45"
    ["marker"]=>
    string(5) "false"
    ["href"]=>
    string(0) ""
    ["bold"]=>
    string(5) "false"
    ["italic"]=>
    string(5) "false"
    ["color"]=>
    string(17) "rgb(62, 201, 106)"
    ["face"]=>
    string(7) "Verdana"
    ["size"]=>
    string(2) "24"
  }
}

I want to print object value like Label0. How can I get it. I am using following code to print label

foreach($video_xml->playlist->video->labels->label as $label){
        var_dump($label);
    }

and I am expecting output as: string(8) "Label1fg" string(6) "Label0" string(6) "Label0"

A SimpleXMLElement object behaves like an object, but is actually a system RESOURCE, (specifically a libxml resource). All its properties are also SimpleXMLElement objects. You need to convert each leaf node to the expected type to get primitive values (strings, f.e.).

foreach ($video_xml->playlist->video->labels->label as $label) {
    var_dump((string)$label);
}

should print what you want.


If the nodes of your XML document do not have attributes and you do only simple operations with it (get data from some nodes), a simpler way to work with it is to use json_encode()/json_decode() to convert it to an multi-level array:

// TRUE as the second argument to json_decode() to get back arrays, not objects
$video_data = json_decode(json_encode($video_xml), TRUE));

foreach ($video_data['playlist']['video']['labels']['label'] as $label) {
    var_dump($label);
}

If you don't pass TRUE as the second argument to json_decode() it returns an object (stdClass) and you can use the existing code to navigate through it.


If you have to operate on the XML document structure, in my opinion it's easier to work with DOMElement and the other DOM classes.