【问题标题】:How to parse xml file using php script [duplicate]如何使用php脚本解析xml文件[重复]
【发布时间】:2018-05-23 05:10:28
【问题描述】:

这是可能的xml文件

<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
<channel>
<title>werwer</title>
<link>werwerwe</link>

<item>
<g:id>704667</g:id>
<title>Nike</title>
<description>erterterter</description>
</item>

<item>
<g:id>4456456</g:id>
<title>Nike</title>
<description>erterterter</description>
</item>

</channel></rss>

如何解析那个 xml 文件,我有脚本但是它不起作用

if (file_exists('products.xml')) {
    $xml = simplexml_load_file('products.xml');

    print_r($xml);
} else {
    exit('Failed to open products.xml.');
}

知道如何在 g:id 之间获取信息吗?

【问题讨论】:

    标签: php xml


    【解决方案1】:

    您需要将命名空间应用到孩子。 http://php.net/manual/en/simplexmlelement.getnamespaces.php

    <?php
    $xml = '<?xml version="1.0" encoding="utf-8"?>
    <rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
        <channel>
            <title>werwer</title>
            <link>werwerwe</link>
    
            <item>
                <g:id>704667</g:id>
                <title>Nike</title>
                <description>erterterter</description>
            </item>
    
            <item>
                <g:id>4456456</g:id>
                <title>Nike</title>
                <description>erterterter</description>
            </item>
    
        </channel>
    </rss>';
    
    $xml = simplexml_load_string($xml);
    $ns = $xml->getNamespaces(true);
    
    foreach ($xml->channel->item as $item) {
        echo $item->children($ns['g'])->id.PHP_EOL;
    }
    /*
    704667
    4456456
    */
    

    https://3v4l.org/t2D84

    【讨论】:

    • 是否可以在不命名的情况下检索xml中的所有数据
    • 不,如果它有命名空间,那么你需要使用它们。为什么?
    • 例如:3v4l.org/iDtYY
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 2012-02-26
    • 1970-01-01
    • 2019-05-15
    相关资源
    最近更新 更多