PHP 可以使用 simplexml_load_stringsimplexml_load_file 來解析 XML, 以取得內容

程式 與 XML 內容

 

<?php
$string = <<<XML
<?xml version='1.0'?>
<document responsecode="200">
<result count="10" start="0" totalhits="133047950">
<title>Test</title>
<from>Jon</from>
<to>Tsung</to>
</result>
</document>
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
取得屬性的值(@attributes)
  • $xml->result->attributes()->totalhits; // 13304
  • $result_attr = $xml->result->attributes();
    $result_attr['totalhits']; // 13304

Source

 

arrow
arrow
    全站熱搜

    James Wu 發表在 痞客邦 留言(0) 人氣()