Files
kiri-wchat/common/Help.php
T
as2252258@163.com baf07b7ab2 add clear
2020-01-09 18:57:08 +08:00

108 lines
1.9 KiB
PHP

<?php
namespace common;
class Help extends Miniprogarampage
{
/**
* @param array $data
* @return string
*/
public static function toXml(array $data)
{
$xml = "<xml>";
foreach ($data as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
} else {
$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
}
}
$xml .= "</xml>";
return $xml;
}
/**
* @param $xml
* @return mixed
*/
public static function toArray($xml)
{
if (is_array($xml)) {
return $xml;
}
if (!is_null($json = json_decode($xml, TRUE))) {
return $json;
}
if (is_array($json)) {
return $json;
}
if (!static::isXml($json)) {
return $json;
}
$data = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
if (is_array($data)) {
return $data;
}
return json_decode(json_encode($data), TRUE);
}
public static function isXml($body)
{
return preg_match('/^<[a-zA-Z_]+>(.*?)?<\/[a-zA-Z_]+>$/', $body);
}
/**
* @param int $length
* @return string
*
* 随机字符串
*/
public static function random($length = 20)
{
$res = [];
$str = 'abcdefghijklmnopqrstuvwxyz';
$str .= strtoupper($str) . '1234567890';
for ($i = 0; $i < $length; $i++) {
$rand = substr($str, rand(0, strlen($str) - 2), 1);
if (empty($rand)) {
$rand = substr($str, strlen($str) - 3, 1);
}
array_push($res, $rand);
}
return implode($res);
}
/**
* @param array $array
* @param $key
* @param $type
* @return string
*/
public static function sign(array $array, $key, $type)
{
ksort($array, SORT_ASC);
$string = [];
foreach ($array as $hashKey => $val) {
if (empty($val)) {
continue;
}
$string[] = $hashKey . '=' . $val;
}
$string[] = 'key=' . $key;
$string = implode('&', $string);
if ($type == 'MD5') {
return strtoupper(md5($string));
} else {
return hash('sha256', $string);
}
}
}