使用php从站点获取数据并放入数组

时间:2013-11-13 19:30:36

标签: php arrays fetch

<div>A/C:front<span style="color:red;margin:8px">/
</span>Anti-Lock Brakes<span style="color:red;margin:8px">/
</span>Passenger Airbag<span style="color:red;margin:8px">/
</span>Power Mirrors<span style="color:red;margin:8px">/
</span>Power Steering<span style="color:red;margin:8px">/
</span>Power Windows<span style="color:red;margin:8px">/
</span>Driver Airbag<span style="color:red;margin:8px">/
</span>No Accidents<span style="color:red;margin:8px">/
</span>Power Door Locks<span style="color:red;margin:8px">/</span>
</div>

在网站上显示如下:

  

A / C:前/防抱死制动/乘客安全气囊/电动后视镜/动力转向/电动车窗/驾驶员安全气囊/无意外/电动门锁/

我使用了$content = file_get_contents('url');,现在我需要转换数据。

我需要获取上面的每个选项并将它们放在一个数组或类似的内容中:

$option = ("A/C:front","Anti-Lock Brakes","Passenger Airbag",....);

知道如何使用php做到这一点吗?

2 个答案:

答案 0 :(得分:0)

使用源代码,一切都变得更容易:

<?php

$dom = new DOMDocument;
@$dom->loadHTMLFile('http://www.sayuri.co.jp/used-cars/B37659-Nissan-Tiida%20Latio-japanese-used-cars');
$xpath = new DOMXPath($dom);
$nodes = iterator_to_array($xpath->query('//h4/following-sibling::div')->item(0)->childNodes);
$items = array_map(function ($node) {
        return $node->nodeValue;
    }, array_filter($nodes, function ($node) {
        return $node->nodeValue != '/';
    }));
var_dump($items);

这给了我以下内容:

array(9) {
  [0]=>
  string(9) "A/C:front"
  [2]=>
  string(16) "Anti-Lock Brakes"
  [4]=>
  string(16) "Passenger Airbag"
  [6]=>
  string(13) "Power Mirrors"
  [8]=>
  string(14) "Power Steering"
  [10]=>
  string(13) "Power Windows"
  [12]=>
  string(13) "Driver Airbag"
  [14]=>
  string(12) "No Accidents"
  [16]=>
  string(16) "Power Door Locks"
}

您可能希望在array_values()上使用$items来重置索引。这就是全部!

答案 1 :(得分:-1)

听起来你需要DOMDocument。具体来说,getElementsByTagName功能。所以使用你的例子,我建议这样做。请根据您的需求进行调整:

// Get the contents of the URL. 
$content = file_get_contents('url');

// Parse the HTML using `DOMDocument`
$dom = new DOMDocument();
@$dom->loadHTML($content);

// Search the parsed DOM structure for `span` elements.
$option = array();    
foreach($dom->getElementsByTagName('span') as $span){
  $option[] = $span->nodeValue;
}

// Dumps the values in `option` for review.    
echo '<pre>';
print_r($option);
echo '</pre>';