本文實例講述了php判斷str字符串是否是xml格式數據的方法。分享給大家供大家參考,具體如下:
<?php //自定義xml驗證函數xml_parser() function xml_parser($str){ $xml_parser = xml_parser_create(); if(!xml_parse($xml_parser,$str,true)){ xml_parser_free($xml_parser); return false; }else { return (json_decode(json_encode(simplexml_load_string($str)),true)); } } //應用示例: $xmlstr=<<<ETO <?xml version="1.0" encoding="UTF-8"?> <books> <book> <author>Jack Herrington</author> <title>PHP Hacks</title> <publisher>O'Reilly</publisher> </book> <book> <author>Jack Herrington</author> <title>Podcasting Hacks</title> <publisher>O'Reilly</publisher> </book> <book> <author>XML數據</author> <title></title> <publisher>tools.jb51.net</publisher> </book> </books> ETO; $jsonstr='{ "tools": [ { "name":"css format" , "site":"http://tools.jb51.net/code/css" }, { "name":"json format" , "site":"http://tools.jb51.net/code/json" }, { "name":"pwd check" , "site":"http://tools.jb51.net/password/my_password_safe" } ] }'; if(xml_parser($xmlstr)){ echo "\$xmlstr是xml格式數據"; }else{ echo "\$xmlstr不是xml格式數據"; } echo "<br/>"; if(xml_parser($jsonstr)){ echo "\$jsonstr是xml格式數據"; }else{ echo "\$jsonstr不是xml格式數據"; } ?>
運行結果:
$xmlstr是xml格式數據 $jsonstr不是xml格式數據
PS:這里再為大家提供幾款關于xml操作的在線工具供大家參考使用:
在線XML/JSON互相轉換工具:
http://tools.jb51.net/code/xmljson
在線格式化XML/在線壓縮XML:
http://tools.jb51.net/code/xmlformat
XML在線壓縮/格式化工具:
http://tools.jb51.net/code/xml_format_compress
XML代碼在線格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat
更多關于PHP相關內容感興趣的讀者可查看本站專題:《PHP針對XML文件操作技巧總結》、《PHP數組(Array)操作技巧大全》、《php字符串(string)用法總結》、《PHP錯誤與異常處理方法總結》、《PHP基本語法入門教程》、《php面向對象程序設計入門教程》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
【網站聲明】本站除付費源碼經過測試外,其他素材未做測試,不保證完整性,網站上部分源碼僅限學習交流,請勿用于商業用途。如損害你的權益請聯系客服QQ:2655101040 給予處理,謝謝支持。