drrog9853
2018-09-17 14:07
浏览 164
已采纳

将HTML响应转换为PHP数组

The response I am getting from a web call in php is something i have never seen. I have tried json_decode function and I have also tried the parse_str below, but I can't get the values to return in an array.

What i want to do is to output an array with name, price, and url. The formatting of the return has got me stumped (I copied it exactly, no typos or missing ' characters).

$urltest='https://www.***';
$result408 = file_get_contents($urltest);
//parse_str($result408, $output);

Prices = [{'name':'Seller1', 'unknown':'unknown0',  'price':60.37, 'price_f':'$60<sup style="font-size:12px;">37</sup>', 'url':'http:…'},
        {'name':'Seller2', 'unknown':'unknown0','price':87.25, 'price_f':'$87<sup style="font-size:12px;">25</sup>, 'url':'http:…'},
        {'name':'Seller3', 'unknown':'unknown0',  'price':74, 'price_f':'$74<sup style="font-size:12px;">00</sup>', 'url':'http:…'}];
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongxi2014 2018-09-17 15:37
    已采纳

    The JSON returned from the service is bad. It looks like you can alter it to make it into JSON that can be parsed. Bear in mind this approach assumes that there are no single quotes in any of the data values.

    $tmp=str_replace('gSellPrices =', '',$result408); $tmp = str_replace('"', '\"', $tmp); $tmp = str_replace('\'', '"', $tmp); $tmp = rtrim($tmp, '; ');

    $urltest='https://www.***';
    $result408 = file_get_contents($urltest);
    // Remove 'Prices = '
    $tmp=str_replace('gSellPrices =', '',$result408);
    // Protect the existing double quotes
    $tmp = str_replace('"', '\\"', $tmp);
    // Now replace all the incorrect single quotes with double quotes.
    $tmp = str_replace('\'', '"', $tmp);
    // Remove trailing semicolon
    $tmp = rtrim($tmp, '; ');
    // Now we can json_decode
    $data = json_decode($tmp);
    
    
    Assuming that the output from service is EXACTLY as follows:
    
    Prices = [{'name':'Seller1', 'unknown':'unknown0',  'price':60.37, 'price_f':'$60<sup style="font-size:12px;">37</sup>', 'url':'http:…'},
        {'name':'Seller2', 'unknown':'unknown0','price':87.25, 'price_f':'$87<sup style="font-size:12px;">25</sup>, 'url':'http:…'},
        {'name':'Seller3', 'unknown':'unknown0',  'price':74, 'price_f':'$74<sup style="font-size:12px;">00</sup>', 'url':'http:…'}];
    
    已采纳该答案
    打赏 评论
  • doujiong3146 2018-09-17 14:43

    You are looking for json_decode ( http://php.net/manual/tr/function.json-decode.php )

    urltest='https://www.***';
    $result408 = file_get_contents($urltest);
    $output = json_decode($result408);
    
    打赏 评论

相关推荐 更多相似问题