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文件 可以获取指定标签中的数据 (->标签)箭头指向哪个标签便获取所在标签中的数据。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步