Home  >  Article  >  Backend Development  >  PHP uses simplexml to parse xml

PHP uses simplexml to parse xml

黄舟
黄舟Original
2017-02-24 15:29:432279browse

php uses simplexml to parse xml

PHP uses simplexml to parse xml

code show as below:


$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>http://www.php.cn/;/loc>
        <lastmod>2013-06-13 01:20:01</lastmod>
        <changefreq>always</changefreq>
        <priority>1.0</priority>
    </url>
    <url>
        <loc>http://www.php.cn/;/loc>
        <lastmod>2013-06-13 01:20:01</lastmod>
        <changefreq>always</changefreq>
        <priority>0.8</priority>
    </url>
</urlset>
XML;

$simple =  simplexml_load_string($xml);
// $url = &#39;http://www.php230.com/baidu_sitemap1.xml&#39;;
// $simple = simplexml_load_file($url);

Here we can check the format of $simple:



print_r($simple);
SimpleXMLElement Object
(
    [url] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [loc] => http://www.php.cn/
                    [lastmod] => 2013-06-13 01:20:01
                    [changefreq] => always
                    [priority] => 1.0
                )
            [1] => SimpleXMLElement Object
                (
                    [loc] => http://www.php.cn/
                    [lastmod] => 2013-06-13 01:20:01
                    [changefreq] => always
                    [priority] => 0.8
                )
        )
)

We can see that the result is in the format of an object or array, so that we can easily obtain the value of each element in XML



foreach ($simple->url as $val){
    print $val->loc;
}

The loc value of each item will be output here.          

The above is the content of PHP using simplexml to parse xml. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
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 admin@php.cn
Previous article:AJAX xmlHttpNext article:AJAX xmlHttp