问题描述
-------------- EDIT ------------------------
--------------EDIT------------------------
所以我要使用DOM方法.这是我到目前为止的内容:
So i am going with the DOM approach. Here is what I have so far:
<?php function getdata(){
$contents = file_get_contents('internatdata.htm');
//create a DOM based off of the string from the html table
$DOM = new DOMDocument;
$DOM->loadHTML($contents);
//get all tr and td
$items = $DOM->getElementsByTagName('tr');
$tds = $DOM->getElementsByTagName('td');
function tdrows($elements){
$str = "";
for ($ii =0; $ii < $elements->length; $ii++){
$str .= $elements->item($ii)->nodeValue . ",";
}
return $str;
}
for ($i = 0; $i < $items->length; $i++){
echo tdrows($tds) . "; <br />";
}
}
?>
我遇到的问题是我只想从每个表行中选择td.我正在尝试通过嵌套循环来实现这一目标.不幸的是,它正在页面上将每个标签的文本打印多少次.我怎么能得到它,所以它只打印每个tr的td而不是dom上的每个td?
The issue I am having is that I only want to select the td's from each table row. I am trying to achieve this with a nested loop. unfortunately It is printing the text of every tag on the page how ever many times as there are tags. how can i get it so its only printing the td of each tr and not every td on the dom?
我需要使用html表作为数据源,因为我无权访问数据库.我认为能够从html表中查询数据,我需要创建一个函数以将表转换为数组或多维数组.
I need to use an html table as the source of my data because I don't have access to the database. I figure to be able to query data from the html table I need create a function to convert the table into an array, or a multidimensional array.
我有基本的想法,但我需要一些帮助来完成代码以基于html表返回数组.
I have the basic Idea I think but I need some help finishing the code to return an array based off the html table.
如果您除了将表转换为数组之外,还有其他更好的方法,请告诉我
Also If you have a better way of doing this other than converting the table to an array then please let me know
这是我到目前为止的想法:
Here is the idea I had so far:
<?php
function getdata(){
$contents = file_get_contents('data.htm');
//add delimiters (semicolon for a row and comma for a cell) ???
$stripped = strip_tags($contents);
//explode into an array based off the delimiters above ???
}
?>
推荐答案
我已经更新了您的修改以进行修复.
I've updated your edit to fix it.
function tdrows($elements)
{
$str = "";
foreach ($elements as $element) {
$str .= $element->nodeValue . ", ";
}
return $str;
}
function getdata()
{
$contents = "<table><tr><td>Row 1 Column 1</td><td>Row 1 Column 2</td></tr><tr><td>Row 2 Column 1</td><td>Row 2 Column 2</td></tr></table>";
$DOM = new DOMDocument;
$DOM->loadHTML($contents);
$items = $DOM->getElementsByTagName('tr');
foreach ($items as $node) {
echo tdrows($node->childNodes) . "<br />";
}
}
getdata();
这篇关于HTML表格到PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!