2012年9月20日 星期四

PHP 使用 SimpleXML 來解析 XML 內容、屬性

PHP 可以使用 simplexml_load_string、simplexml_load_file 來解析 XML, 以取得內容. 程式 與 XML 內容

  
    Test
    Jon
    Tsung
  

XML;
 
$xml = simplexml_load_string($string);
print_r($xml);
?>
XML 解析 的 內容會回傳一個物件
SimpleXMLElement Object
(
    [@attributes] => Array
    (
       [responsecode] => 200
    )
 
    [result] => SimpleXMLElement Object
    (
        [@attributes] => Array
        (
            [count] => 10
            [start] => 0
            [totalhits] => 13304
        )
 
       [title] => Test
       [from] => Jon
       [to] => Tsung
    )
)
如何取用此物件回傳的值
取得 result 下的 title
$xml->result->title; // Test (object)
建議: (string)$xml->result->title; // 強迫轉換成字串
取得屬性的值(@attributes)
$xml->result->attributes()->totalhits; // 13304 (object), 一樣建議於前面加 (string)

$result_attr = $xml->result->attributes();
$result_attr['totalhits']; // 13304 (object), 一樣建議於前面加 (string)
原文來源:http://blog.longwin.com.tw/2009/10/php-simplexml-parse-attr-content-2009/

沒有留言: