2012-11-23 10 views
0

我想使用phpQuery來解析DOM元素。這裏是我想要使用PHP遞歸函數導入MySQL數據庫的the HTML treeHTML ul/li使用phpQuery的PHP數組樹

MySQL數據庫將存儲樹類(含子,子,...,類別)

create table categories 
(
    categorie_id int(11) primary key auto_increment, 
    categorie_id_parent int(11) not null, 
    categorie_nom varchar(255) not null 
) 

這裏是我的僞代碼:

function getCategories($pq_object, $last_generated_mysql_id) 
{ 
    // for every element of $pq_object on same lvl 
    { 
     // insert into mysql $pq_object->a->name 
     // and with categorie_id_parent as $last_generated_mysql_id if has parent 

     // going deeper for every child 
     getCategories($pq_object->children(), mysql_insert_id()); 
    } 
} 

謝謝你的幫助

回答

1

我其實做到了:

function getCats($categorie_id_parent, $cats) 
{ 
    echo "<ul>"; 

    foreach ($cats as $ch) 
    { 
     $categorie_nom = mysql_real_escape_string(pq($ch)->find("a:first")->text()); 

     // Inserting categories 
     $query_categorie = "SELECT categorie_id FROM categories WHERE categorie_id_parent='".$categorie_id_parent."' AND categorie_nom LIKE '".$categorie_nom."' LIMIT 1"; 
     $result_categorie = mysql_query($query_categorie) or die (mysql_error()); 

     $categorie_id = 0; 

     if (mysql_num_rows($result_categorie)) 
     { 
      $row_categorie = mysql_fetch_assoc($result_categorie); 

      $categorie_id = $row_categorie['categorie_id']; 
     } 
     else 
     { 
      $query_insert = "INSERT INTO categories (categorie_id_parent, categorie_nom) VALUES ('".$categorie_id_parent."', '".$categorie_nom."')"; 
      mysql_query($query_insert) or die (mysql_error()); 

      $categorie_id = mysql_insert_id(); 
     } 

     // if we have any subcategories 
     if (pq($ch)->children()->children()->length) 
     { 
      echo "<li>".pq($ch)->find("a:first")->text()."</li>"; 

      // going deeper 
      getCats($categorie_id, pq($ch)->children()->children()); 
     } 
     // If no subcategories, show the last link name and href 
     else 
      echo "<li>".pq($ch)->find('a:first')->text()." ".pq($ch)->find('a:first')->attr('href')."</li>"; 
    } 

    echo "</ul>"; 
}