Home  >  Article  >  Backend Development  >  How to convert PHP-xml & jsonp to array

How to convert PHP-xml & jsonp to array

藏色散人
藏色散人forward
2019-12-04 13:32:082539browse

1. Convert xml to array, xml contains 706a388e39e8555a9742f4594c5343bf tag

/**
 * 将xml转换为数组
 * @param string $xml:xml文件或字符串
 * @return array
 */
function xmlToArray($xml){
//考虑到xml文档中可能会包含<![CDATA[]]>标签,第三个参数设置为LIBXML_NOCDATA
if (file_exists($xml)) {
libxml_disable_entity_loader(false);
$xml_string = simplexml_load_file($xml,&#39;SimpleXMLElement&#39;, LIBXML_NOCDATA);
}else{
libxml_disable_entity_loader(true);
$xml_string = simplexml_load_string($xml,&#39;SimpleXMLElement&#39;, LIBXML_NOCDATA);
}
$result = json_decode(json_encode($xml_string),true);
return $result;
}

2. Convert jsonp to array

/**
 * 把jsonp转为php数组
 * @param string $jsonp jsonp字符串
 * @param boolean $assoc 当该参数为true时,将返回array而非object
 * @return array
 */
function jsonp_decode($jsonp, $assoc = false)
{
    $jsonp = trim($jsonp);
    if(isset($jsonp[0]) && $jsonp[0] !== &#39;[&#39; && $jsonp[0] !== &#39;{&#39;) {
        $begin = strpos($jsonp, &#39;(&#39;);
        if(false !== $begin)
        {
            $end = strrpos($jsonp, &#39;)&#39;);
            if(false !== $end)
            {
                $jsonp = substr($jsonp, $begin + 1, $end - $begin - 1);
            }
        }
    }
    return json_decode($jsonp, $assoc);
}

Related recommendations: "PHP Tutorial"

The above is the detailed content of How to convert PHP-xml & jsonp to array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete