我有兩個腳本,一個用於從我的系統中擦除一些HTML輸出並返回一個數據數組(本例中爲錦標賽)。當我var_dump
這個數組,你得到以下輸出。PHP中非法的字符串偏移值 - 只有兩個字段失敗
array(66) {
[0]=>
array(4) {
["date"]=>
string(14) "2 January 2017"
["tournament"]=>
string(43) "Brisbane International presented by Suncorp"
["surface"]=>
string(10) "Hard Court"
["venue"]=>
string(8) "Brisbane"
}
[1]=>
array(4) {
["date"]=>
string(14) "2 January 2017"
["tournament"]=>
string(19) "Aircel Chennai Open"
["surface"]=>
string(10) "Hard Court"
["venue"]=>
string(7) "Chennai"
}
這裏是獲取數據
function processTournamentHTML($url) {
$domOb = new DomDocument();
$html = $domOb->loadHTMLFile($url);
$domOb->preserveWhiteSpace = false;
$container = $domOb->getElementsByTagName('tr');
$tournaments = array(); // BLANK ARRAY TO POPULATE
// PROCESS THE TOURNAMENT HTML INTO A PHP ARRAY
foreach($container as $row) {
$items = $row->getElementsByTagName('td');
$tournaments[] = array(
"date" => $items->item(0)->nodeValue,
"tournament" => $items->item(1)->nodeValue,
"surface" => $items->item(2)->nodeValue,
"venue" => $items->item(3)->nodeValue
);
}
echo "Processing the following URL: " . $url;
return $tournaments;
}
這插入腳本上述數據到我的數據庫(所有樣本數據)的腳本。
function processTournaments($tournaments, $tour) {
// OPEN CONNECTION
$conn = mysqli_connect("test", "test", "test", "test");
foreach($tournaments as $tournament) {
$date = $tournament["date"];
$tournament = $tournament["tournament"];
$surface = $tournament["surface"];
$venue = $tournament["venue"];
$sql = "INSERT INTO data_table (date, tournament, surface, venue, tour) VALUES ($date, $tournament, $surface, $venue, $tour)";
$query = mysqli_query($conn, $sql);
}
// CLOSE DB CONNECTION
mysqli_close($conn);
return "Finished processing for " . $tour;
}
我我的代碼運行在URL/TO/FILE.php
$tournaments = processTournamentHTML($url);
processTournaments($tournaments, "tournament_code");
正如你可以看到我的樣本數據具有66
記錄,我得到這些錯誤66次:
Warning: Illegal string offset 'surface' in URL/TO/FILE.PHP on line 47
Warning: Illegal string offset 'venue' in URL/TO/FILE.PHP on line 48
並且正在處理的示例HTML
<tr>
<td rowspan="3" width="133">2 January 2017</td>
<td width="294">Brisbane International presented by Suncorp</td>
<td width="90">Hard Court</td>
<td width="121">Brisbane</td>
</tr>
<tr>
<td rowspan="3" width="133">2 January 2017</td>
<td width="294">Shenzhen Open</td>
<td width="90">Hard Court</td>
<td width="121">Shenzhen</td>
</tr>
解決
我終於解決了這個,因爲我用的是下面的代碼:
foreach($tournaments as $tournament) {
$date = $tournament["date"];
$tournament = $tournament["tournament"]; // WHEN YOU SEE IT
$surface = $tournament["surface"];
$venue = $tournament["venue"];
}
當你看到它,它很煩人。我在我的foreach中使用$tournament
作爲變量,它覆蓋了我所在的$tournament
索引。 -_-
您獲取DOM窗體的$ url是否具有所需的3和4表格單元? – dsadnick
是的 - 我會在帖子上面發帖,道歉。 – WebDevDanno
@dsadnick修正 – WebDevDanno