使用PHP阅读Google XML文件

时间:2017-10-22 13:29:16

标签: php xml

我需要你的帮助,因为我是PHP的初学者,我需要从下面的Google产品Feed中提取信息,如何获得标题或链接?

我尝试使用simplexml_load_file,但是使用简单的foreach我找不到隔离单个元素的正确方法。

提前谢谢

<xml version="1.0">
    <rss version="2.0" xmlns:g="http://base.google.com/ns/1.0">
        <channel>
            <title>Title</title>
            <description>Products Brand</description>
            <link>http://www.website.com/</link>
            <item>
                <g:id>1111111</g:id>
                <g:gtin>111111</g:gtin>
                <title>Lorem ipsum dolor sit amet</title>
                <description>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent in orci efficitur lorem aliquam iaculis non nec orci. Aliquam mattis suscipit nisi in faucibus. Nullam ex mauris, mollis at tellus at, pulvinar mollis orci.</description>
                <g:google_product_category>Apparel &amp; Accessories &gt; Shoes</g:google_product_category>
                <g:product_type>Women &gt; New Arrivals &gt; New Arrivals</g:product_type>
                <link>http://www.brand.com/product.html</link>
                <g:image_link>https://www.brand.com/image_00.png</g:image_link>
                <g:additional_image_link>https://www.brand.com/image_00.png</g:additional_image_link>
                <g:condition>new</g:condition>
            </item>

1 个答案:

答案 0 :(得分:1)

XML略有错误,xml应为<?xml version="1.0"?>,并且我添加了任何缺失的结束标记。所以显示一些位的代码是......

$xml = simplexml_load_file("NewFile.xml");

foreach ( $xml->channel as $channel )   {
    foreach ( $channel->item as $item ){
        $title = (string)$item->title;
        $link = (string)$item->link;
        echo $title." => ".$link.PHP_EOL;
    }
}

所有这些都是针对每个<channel>元素的foreach,然后是foreach,以获取其中每个<item>元素的详细信息。