PHP之SimpleXML函数

使用php创建XML文件十分简单,使用SimpleXML那就更简便了,同时读取XML文件也十分方便。XML文件是直接在浏览器中打开,以自定义标签的方式直观简洁的方式展示给读者。

1.创建XML文件

header("Content-type: text/html; charset=utf-8"); 
    $xml=new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><returnRequest />');
    $item=$xml->addchild("client","DYSON");
    $item1=$xml->addchild("distributionCentre","DAMCO");
    
    $item2=$xml->addchild("order");
    $item2->addchild("ref",$info_all['id']);
    $item2->addchild("id","??");
    $item2->addchild("store","CN");
        $item3 = $item2->addchild("detail");
            $item3->addchild("created",$info_all['crated']);
            $item3->addchild("customer");
            $item3->addchild("ip");
            $item3->addchild("language","cn-GB");
            $item3->addchild("vatCountry","CN");
            $item3->addchild("origin","DYSON");
            $item3->addchild("originDate",$info_all['crated']);
            $item3->addchild("customerReference","???");
            $item3->addchild("csAgent");
        $item4 = $item2->addchild("people");
            $item4_1 = $item4->addchild("person");
            $item4_1->addchild("ref");
            $item4_1->addchild("title");
            $item4_1->addchild("firstName",$info_all['receiver_name']);
            $item4_1->addchild("lastName");
            $item4_1->addchild("phone",$info_all['receiver_mobile']);
            $item4_1->addchild("fax");
            $item4_1->addchild("mobile");
            $item4_1->addchild("email");
            $item4_1->addchild("department");
            $item4_1->addchild("companyName");
            $item4_1->addchild("gender");
            $item4_1->addchild("dateofbirth");
        $item5 = $item2->addchild("address");
            $item5_1 = $item5->addchild("address");
            $item5_1->addchild("addresstype","customer");
            $item5_1->addchild("addrss1",$info_all['receiver_district']);
            $item5_1->addchild("addrss2",$info_all['receiver_address']);
            $item5_1->addchild("city",$info_all['receiver_city']);
            $item5_1->addchild("state",$info_all['receiver_state']);
            $item5_1->addchild("zip",$info_all['receiver_zip']);
                $item5_1_1 = $item5_1->addchild("country");
                $item5_1_1->addchild("code","CN");
                $item5_1_1->addchild("name","CHINA");
            
        
        
        
    header("Content-type: text/xml");
    // echo $xml->asXml();exit;
    $xml->asXml("test.xml");

使用addchild方法可以无限创建XML标签,同时也可以无限层级,类似多维数组形式。文件打开显示为

2.解析XML文件

$xml = simplexml_load_file("test.xml");
    
     $data['client'] = $xml->client;
     $data['language'] = $xml->order->detail->language;

     echo $data['language'];

使用 simplexml_load_file 函数可以解析XML文件 可以获取指定标签中的数据 (->标签)箭头指向哪个标签便获取所在标签中的数据。

原文地址:https://www.cnblogs.com/xionghao/p/6899227.html