How to convert PHP-xml & jsonp to array

藏色散人
Release: 2023-04-07 22:08:01
forward
2486 people have browsed it

1. Convert xml to array, xml contains tag

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

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] !== '[' && $jsonp[0] !== '{') {
        $begin = strpos($jsonp, '(');
        if(false !== $begin)
        {
            $end = strrpos($jsonp, ')');
            if(false !== $end)
            {
                $jsonp = substr($jsonp, $begin + 1, $end - $begin - 1);
            }
        }
    }
    return json_decode($jsonp, $assoc);
}
Copy after login

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!

Related labels:
php
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!