我正在尝试下载产品图片或获取 XML 格式的文件路径。我有同名的麻烦。谢谢。
XML 文件
-<products>
-<product>
<product_code>AXX-655</product_code>
<product_name>Samsung Led TV</product_name>
-<Images>
<Image>https://max.cloud/37233/products-77d4.jpg</Image>
<Image>https://max.cloud/37233/products-254789.jpg</Image>
<Image>https://max.cloud/37233/products-f010.jpg</Image>
<Image>https://max.cloud/37233/products-8004.jpg</Image>
</Images>
-</product>
-<product>
<product_code>ACH-645</product_code>
<product_name>LG Led TV</product_name>
-<Images>
<Image>https://max.cloud/37233/products-895777.jpg</Image>
<Image>https://max.cloud/37233/products-3652.jpg</Image>
<Image>https://max.cloud/37233/products-k0120.jpg</Image>
</Images>
-</product>
-</products>
我正在尝试通过产品 ID 或产品名称下载产品图片 PHP文件
$xml = simplexml_load_file($xmllocalurl) or die("Error: Cannot create object");
foreach ($xml->children() ->children() as $child) {
$name = $child->product_name;
$url = $child->Images->Image;
$img = 'imgfiles/'.$name.'.jpg';
$url = $child->product_name;
file_put_contents($img, file_get_contents($url));
由于您正在处理 xml,您最好使用 xpath 来提取我认为是您的目标数据的内容。
以下只是展示数据;然后你可以按照你认为合适的方式保存它:
$items = $xml->xpath('//product');
foreach ($items as $item) {
$name = $item->xpath('./product_name')[0];
$code = $item->xpath('./product_code')[0];
$images = $item->xpath('.//Image/text()');
echo $name," " ,$code," " ;
foreach ($images as $image) {
echo $image , " ";
}
echo "\r\n";
};
输出(基于您的示例 xml):
Samsung Led TV AXX-655 https://max.cloud/37233/products-77d4.jpg https://max.cloud/37233/products-254789.jpg https://max.cloud/37233/products-f010.jpg https://max.cloud/37233/products-8004.jpg
LG Led TV ACH-645 https://max.cloud/37233/products-895777.jpg https://max.cloud/37233/products-3652.jpg https://max.cloud/37233/products-k0120.jpg