我有以下xml文件,我使用php simplexml来解析数据:
<?xml version="1.0"?>
<root>
<update_time>2014-06-09</update_time>
<item>
<url>http://www.myproducts.com</url>
<name>Wireless Bluetooth Speaker - White</name>
<category>
<parent_id>53</parent_id>
<parent_name>Electronics</parent_name>
<category_id>150</category_id>
<category_name>Mini Speaker</category_name>
<parent_id>81</parent_id>
<parent_name>Bluetooth Function Devices</parent_name>
<category_id>1384</category_id>
<category_name>Bluetooth Function Speaker</category_name>
</category>
<media>
<images>http://www.myshop.com/media/catalog/product/f/i/file_2111_316.jpg</images>
<images>http://www.myshop.com/media/catalog/product/f/i/file_2112_260.jpg</images>
</media>
<short_description>
<![CDATA[<p><span style="font-size: small;"><span style="font-family: Arial;">This mini speaker is in unique cup appearance model design. </span></span></p>]]>
</short_description>
<description>
<![CDATA[<p><strong><span style="font-size: small;"><span style="font-family: Arial;">Features:</span></span></strong>
* Special tablet PC<br />
* Protect your tablet screen from dust and hand print<br />
* Size: 17.3 x 10.5cm</span></span></p>
<p><span style="font-size: small;"><span style="font-family: Arial;">Package included:<br />
1* Screen protective film <br />
</span></span></p>]]>
</description>
</item>
</root>
我的php代码如下:
<?php
if(file_exists('feed.xml'))
{
$xml = simplexml_load_file('feed.xml', 'SimpleXMLElement', LIBXML_NOCDATA);
}
foreach($xml->item as $products)
{
echo 'URL:' . (string)$products->url .'<br />';
echo 'Name:' . (string)$products->name .'<br />';
echo 'Category_ID:' . (string)$products->category->category_id .'<br />';//for subcategory
echo 'Category_Name:' . (string)$products->category->category_name .'<br />';
echo 'Images:' . (string)$products->media->images .'<br />';
echo 'Short Description:' . strip_tags((string)$products->short_description) .'<br />'.'<br />';
echo 'Description:' . strip_tags((string)$products->description) .'<br />';
echo '<br />';
}
我正确地获取元素,除了节点 - 类别和媒体下的项目。类别有多个category_id和category_name项,类似的媒体有多个图像。
使用我目前的代码,我能够只获得中的第一项
category->category_id, (category_id =150)
category->category_name (Category_Name:Mini Speaker )
media->images (http://www.myshop.com/media/catalog/product/f/i/file_2111_316.jpg)
我缺少什么?请求帮助......
答案 0 :(得分:1)
而不是强制转换为字符串,强制转换为数组:
$category_id = (array) $products->category->category_id;
$category_name = (array) $products->category->category_name;
因此,您将获得一系列可以使用的值。
如果您只想显示这些值,请使用implode:
echo 'Category_ID:' . implode( ' ', (array) $products->category->category_id ) . '<br />';