如何解析这个XML?

时间:2013-06-11 11:30:45

标签: php xml html5 parsing simplexml

示例网址http://catalog.viglink.com/vigcatalog/products.xml?key=MY_KEY&keyword=samsung 内容如下所示:http://pastebin.com/cLQ0guuV

我只能到这里

<?php
DEFINE (VIGLINK_API_KEY,'YOUR_API_KEY',true);
function parsing_xml($url){
    libxml_use_internal_errors(1);
    $xml = simplexml_load_file($url);
    $data = json_decode(json_encode($xml),true);
    return $data;
}
function viglink_get_products($query){
    $url = 'http://catalog.viglink.com/vigcatalog/products.xml?key=' . VIGLINK_API_KEY . '&keyword=' . urlencode($query);
    $data = parsing_xml($url);
    return $data;
}

$data = viglink_get_products('dewalt');
echo '<pre>';
print_r($data);`

`

我想展示产品,xml的价格。请帮我继续php?

1 个答案:

答案 0 :(得分:1)

你为什么使用$data = json_decode(json_encode($xml),true);

如果你想要一个json内容,那么你的URL应该是

http://catalog.viglink.com/vigcatalog/products.json?xxxx
                                                 ^
                                                 |+--- json not xml 

解决方案

$url = 'http://catalog.viglink.com/vigcatalog/products.json?key=YOUR_KEY&keyword=samsung';
$data = json_decode(file_get_contents($url));
foreach($data->resources->merchants->merchant as $merchant) {
    printf("%s \n", $merchant->name);
}

输出

Newegg.com 
Wireless Emporium 
TigerDirect 
.....
Pixmania 
pcRUSH.com 
Barnes & Noble 
MyGofer 

获得奖品

foreach($data->results->products->product as $product) {
    printf("%s ... %0.2f-%0.2f\n", substr($product->name,0,30), $product->price_min, $product->price_max);
}

输出

Samsung 16GB Galaxy Tab 2 Wi-F ... 299.99-429.00
SAMSUNG Galaxy 5" White/Black  ... 267.26-267.26
Samsung 20.3MP Compact Digital ... 309.99-699.99
Samsung 26" Class 720p 60Hz LE ... 329.99-329.99
Samsung - DualView DV300F 160- ... 134.50-156.99
Samsung 20" S20B350H Widescree ... 138.99-179.74
Samsung HMX-H300 Black High De ... 299.99-399.99
Samsung 20.3MP Compact Digital ... 334.00-699.00
OtterBox Defender Series for S ... 30.64-59.99
Samsung 22" S22B150N LED-LCD F ... 129.91-173.91
Samsung Galaxy S II I9100 Unlo ... 426.95-479.99
Samsung Camera Samsung W300, Y ... 99.00-159.00
Samsung 24" T24B350ND LED-LCD  ... 159.99-249.99
Samsung PL120 14.2 Megapixel C ... 3.99-136.52
Samsung DP700A7D-S03US AIO Cor ... 1599.00-2039.96
Samsung Smart ST200F 16.1 Mega ... 119.99-160.88
Samsung 720p HD Flash Camcorde ... 149.99-149.99
Samsung 40" Class 1080p 120Hz  ... 699.88-797.99
Samsung ST65 14.2 MP Silver Co ... 78.00-78.00
Samsung NP900X4C 15" LED Noteb ... 1723.99-2266.31