星期六, 4月 17, 2010

PHP SimpleXML用法之三

XPath可以參照XML XPath的選擇節點語法這裡當然也可以參照W3C網站上的資料更清楚。


如何在SimpleXML中調用XPath的結果(範例請用之2那一個):
<?php
    /*** create a SimpleXML object ***/
    if( ! $xml = simplexml_load_file("address.xml") )
    {
        echo "Unable to load XML file";
    }
    else
    {
        /*** show the firstname element from all nodes ***/
        print_r($xml->xpath("/users/user/firstname"));
    }
?>
這一個XPath句法可以將users->user->firstname取出,得到

Array
(
    [0] => SimpleXMLElement Object
 (
     [0] => Sheila
 )

    [1] => SimpleXMLElement Object
 (
     [0] => Bruce
 )

    [2] => SimpleXMLElement Object
 (
     [0] => Davo
 )

    [3] => SimpleXMLElement Object
 (
     [0] => Shazza
 )
)
下面則說明如何把Object中的物件取出

<?php
    error_reporting(E_ALL);

    /*** create a SimpleXML object ***/
    if( ! $xml = simplexml_load_file("address.xml") )
    {
        echo "Unable to load XML file";
    }
    else
    {
        /*** show the firstname element from all nodes ***/
        $info = $xml->xpath("//*[firstname='Sheila']");

        /*** fetch the email address ***/
        echo $info[0]->contact->email;
    }
?>
最後我們說明把,SimpleXML的結果存入XML檔案中
<?php
    /*** create a SimpleXML object ***/
    if( ! $xml = simplexml_load_file("address.xml") )
    {
        echo "Unable to load XML file";
    }
    else
    {
        /*** show the firstname element from all nodes ***/
        $info = $xml->xpath("//*[firstname='Sheila']");

        /*** initialize the string ***/
        $xml_string = '';

        /*** loop over the results ***/
        while(list( , $node) = each($info))
        {
            $xml_string .= $node->asXML(); // <c>text</c> and <c>stuff</c>
        }

        /*** output the xml ***/
        echo $xml_string;
    }
?>
利用asXML()得到結果為

<user>
    <firstname>Sheila
    <surname>Green
    <address>2 Good St
    <city>Campbelltown
    <country>Australia
    <contact>
      <phone type="mobile">1234 1234
      <url>http://example.com
      <email>pamela@example.com
    </contact>
  </user>
出處:http://www.phpro.org/tutorials/Introduction-To-SimpleXML-With-PHP.html#10
                                                                    update : 2010/3/25

沒有留言:

張貼留言