1

如果数据是这样的,我如何从文件中读取数据。

<area shape="poly" alt="1101" coords="1735,606, 1736,606, 1737,606, 1738,606, 1739,606, 1740,606, 1741,607,

我知道如何打开文件以及如何简单地读取和存储数据,但是如何从“alt”和“coords”中提取数据,请帮帮我。

<?php
    $handle = @fopen("sunset_map.map", "r");
    $conn = mysql_connect("localhost","root",""); 
    mysql_select_db("read_data",$conn);
    while (!feof($handle)) // Loop til end of file.
    {

    $buffer = fgets($handle, 4096);
    // Read a line.
    // $a = $_get['alt']  ;
    // $b = $_get['coords'];
    // parse_str("alt = str& coords = ",$myarray);
    // print_r($myarray);
    list($a,$b)=explode("|",$buffer);
    // list($myarray)=explode("|",$buffer);
    //Separate string by the means of |
    // echo $a."-".$b."<br>";
    $sql = "INSERT INTO content_data (id,coords) VALUES('".$a."','".$b."')";   
    mysql_query($sql,$conn) or die(mysql_error());

    }
?>
4

3 回答 3

1

It looks like the file is XML data. If so, use the XMLReader interface to get the area nodes something like this:

$sb = new XMLReader;
$sb->open( "sunset_map.map" );
if( $sb === FALSE ) {
    print "Error: Can't open the file. Aborting.\n";
    exit(1);
}

    // find the first area element
    while( $sb->read() && $sb->name !== 'area' )
      ;

    while( $sb->name == 'area' ) {
       // get the attributes you need
       $coords = $sb->getAttribute('coords');
       // Now split the $coords string with explode and whatever
       // and do your inserts

       $sb->next('area');
    }
于 2013-06-28T15:02:06.817 回答
1

使用正则表达式:

$text = '<area shape="poly" alt="1101" coords="1735,606, 1736,606, 1737,606, 1738,606, 1739,606, 1740,606, 1741,607" />';
if (preg_match("/area shape=\"poly\" alt=\"(.*)\" coords=\"(.*)\" /sUSi", $text, $data) {
echo $data[0] . ' ' . $data[1] . ' ' . $data[2];
}
于 2013-06-28T14:58:53.107 回答
1

您可以使用DOMDocument来解析 HTML。使用DOMDocument::getElementsByTagName获取区域元素。然后,当您遍历这些元素时,您可以使用DOMElement::getAttribute来获取“alt”和“coords”属性。

于 2013-06-28T14:55:53.337 回答