Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

PHP get values from SimpleXMLElement array

I have this:

  [1]=>
object(SimpleXMLElement)#6 (1) {
  ["@attributes"]=>
  array(14) {
    ["name"]=>
    string(5) "MySQL"
    ["acknowledged"]=>
    string(1) "1"
    ["comments"]=>
    string(1) "1"
    ["current_check_attempt"]=>
    string(1) "1"
    ["downtime"]=>
    string(1) "0"
    ["last_check"]=>
    string(19) "2010-05-01 17:57:00"
    ["markdown_filter"]=>
    string(1) "0"
    ["max_check_attempts"]=>
    string(1) "3"
    ["output"]=>
    string(42) "CRITICAL - Socket timeout after 10 seconds"
    ["perfdata_available"]=>
    string(1) "1"
    ["service_object_id"]=>
    string(3) "580"
    ["state"]=>
    string(8) "critical"
    ["state_duration"]=>
    string(6) "759439"
    ["unhandled"]=>
    string(1) "0"
  }
}

(I used var_dump($child) to generate that)

How do I get the 'name' attribute out of there as a string?

Here is my code:

$xml = simplexml_load_string($results);

foreach($xml->data->list as $child) {
var_dump($child);
  echo $child->getName() . ": " . $child->name . "<br />";
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...