2

Web サイトから mysql データベースにデータを保存しようとしています。保存したかったほとんどのものを保存できましたが、特定の問題があります。抽出したリンクは保存されていますが、リンクを他の属性と同じ行に配置したいです。以下は、情報を抽出してデータベースに保存するための CURL および mysql クエリです。

$target_url = "http://www.ucc.ie/modules/descriptions/BM.html";
$codeS = "BM";
$html = file_get_contents("http://www.ucc.ie/modules/descriptions/BM.html"); 
@$doc = new DomDocument(); 
@$doc->loadHtml($html); 
//discard white space   
@$doc->preserveWhiteSpace = false; 
$xpath = new DomXPath($doc);

//Read through dd tags
$options = $doc->getElementsByTagName('dd');

//Go into dd tags and look for all the links with class modnav 
$links = $xpath->query('//dd //a[@class = "modnav"]'); 

//Loop through and display the results for links
foreach($links as $link){    
echo $link->getAttribute('href'), '<br><br>';
}   

foreach ($options as $option) { 

    $option->nodeValue;
    echo "Node Value (Module name/title)= $option->nodeValue <br /><br /> <br />"; 

      // save both for each results into database
$query3 = sprintf("INSERT INTO all_modulenames(code,module_name,description_link,gathered_from) 
     VALUES ('%s','%s','%s','%s')",
     mysql_real_escape_string ($codeS),
     mysql_real_escape_string($option->nodeValue),
     mysql_real_escape_string($link->getAttribute('href')),
     mysql_real_escape_string($target_url));
     mysql_query($query3) or die(mysql_error()."<br />".$query3); 

    } 
    echo "<br /> <br /> <br />";


Here is the table
-- ----------------------------
-- Table structure for `all_modulenames`
-- ----------------------------
DROP TABLE IF EXISTS `all_modulenames`;
CREATE TABLE `all_modulenames_copy` (
`code` varchar(255) NOT NULL,
`module_name` varchar(255) NOT NULL,
`description_link` varchar(255) NOT NULL,
`gathered_from` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of all_modulenames
-- ----------------------------

したがって、問題は、「$link->getAttribute('href')」が、保存しようとしている他のコンテンツとは別に保存されていることです。リンクが最初に保存され、次に残りのデータが続き、いくつかの行が空のままになりますが、しようとしていますすべてを一度に保存します。つまり、各行を埋めて、for each ステートメントが終了するまで 2 番目の行に移動します。どうすればこれを行うことができますか? どんな助けでも大歓迎です!!

4

1 に答える 1

1

テストされていません(デバッグが必要です)が、私は次のようなアプローチをとります:

...etc
@$doc->preserveWhiteSpace = false;  

//Read through dd tags 
$options = $doc->getElementsByTagName('dd'); 

foreach ($options as $option) {  

    // Get the links and find the one with the right class
    $href = '';
    $links = $option->getElementsByTagName('a');
    foreach ($link as $link) {
        if ($link->hasAttribute('class') && $link->hasAttribute('href')) {
            $aClasses = explode(' ', $link->getAttribute('class'));
            if (in_array('modnav', $aClasses)) {
                  $href=$link->getAttribute('href');
            }
        }
    }

    Insert in to SQL etc, $href is the link text belonging to the dd ...
于 2012-06-25T02:36:05.237 に答える