2010-05-01 72 views
1

我有這樣得到的值:從PHP的SimpleXMLElement陣列

[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" 
    } 
} 

(我用的var_dump($子)來生成)

如何獲得「名字」有屬性出作爲串?

這裏是我的代碼:

$xml = simplexml_load_string($results); 

foreach($xml->data->list as $child) { 
var_dump($child); 
    echo $child->getName() . ": " . $child->name . "<br />"; 
    } 

回答

12

用SimpleXML,你可以得到:

  • 子元素,使用對象符號:$element->subElement
  • 和屬性,使用數組表示法:$element['attribute']


所以,在這裏,我說你不得不使用:

echo $child['name']; 


作爲參考,並且一對夫婦的例子,看到了SimpleXML手冊的Basic usage部分。

示例#6應該是有趣的一個,關於屬性。

+0

我有這個確切的問題,我不得不爲了得到他們作爲字符串添加'(串)'中的所有屬性的前面。很混亂。 (謝謝,PHP!)編輯:我剛剛意識到JW。下面說同樣的事情。無論如何,希望這有助於那些急於找到正確答案的人,而不要看其他任何答案。 – HartleySan 2016-05-19 16:47:22

0

的凌亂類,但我用這個成功

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

不知道爲什麼,但OpsView API返回一個二維數組,而不是僅僅有每個XML節點:(

echo $child['name']; 
一個價值

作品,是更優雅,謝謝

13

雖然你可以這樣做:。

echo $child['name']; 

看到的值,你應該注意到$child['name']是一個對象,而不是一個字符串。回聲將它轉換爲一個字符串,所以它適用於這種情況。但是,如果你的地方存放,最好將它轉換爲字符串自己:

$name = (string) $child['name']; 
0

我有一個類似的問題,我需要得到串出我的SimpleXMLElement的,我找不到名稱稱它。找到了解決辦法,通過使用(串),以獲取字符串文本:

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)