0
<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>

在网站上显示如下:

空调:前/防抱死刹车/乘客安全气囊/电动后视镜/动力转向/电动车窗/驾驶员安全气囊/无事故/电动门锁/

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

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

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

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

4

2 回答 2

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()on$items来重置索引。就这样!

于 2013-11-13T21:02:18.727 回答
-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>';
于 2013-11-13T19:37:28.440 回答