Maison  >  Article  >  développement back-end  >  Méthode PHP pour déterminer si la chaîne str est une donnée au format XML (explication détaillée)

Méthode PHP pour déterminer si la chaîne str est une donnée au format XML (explication détaillée)

墨辰丷
墨辰丷original
2018-05-19 09:16:301507parcourir

这篇文章主要介绍了php判断str字符串是否是xml格式数据的方法,结合实例形式较为详细的分析了php采用自定义函数针对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&#39;Reilly</publisher>
  </book>
  <book>
    <author>Jack Herrington</author>
    <title>Podcasting Hacks</title>
    <publisher>O&#39;Reilly</publisher>
  </book>
  <book>
    <author>XML数据</author>
    <title>PHP中文网</title>
    <publisher>tools.jb51.net</publisher>
  </book>
</books>
ETO;
$jsonstr=&#39;{ "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" } ] }&#39;;
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格式数据

相关推荐:

php中substr字符串截取函数的用法示例 

PHP使用strstr()函数获取指定字符串后所有字符的方法,strstr字符串_PHP教程

php array数组的相关处理函数and str字符串处理与正则表达式

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn