За последние 24 часа нас посетили 49958 программистов и 1733 робота. Сейчас ищут 697 программистов ...

Пишу простенький парсер. Проблема с записью результатов в БД

Тема в разделе "PHP для новичков", создана пользователем sharunm, 16 ноя 2014.

  1. sharunm

    sharunm Активный пользователь

    С нами с:
    16 ноя 2014
    Сообщения:
    58
    Симпатии:
    0
    Опишу задачу: взять с определенной страницы артикулы (коды деталей), наименования, а записать в БД с названиями марки и моделей автомобиля. Задачу решаю с помощью simple_html_dom.php. Я в php новичок. Просто выдергивать информацию с помощью этого класса научился, записывать в БД тоже, но как только дело дошло до того, чтобы в БД сразу дописать еще пару полей, возникли проблемы:
    Код (Text):
    1.  
    2. <?php
    3. // example of how to use advanced selector features
    4. include('../config.php');
    5. include('../simple_html_dom.php');
    6. $page_adress='некий адрес сайта';
    7. $car='Chery';
    8. $model='Amulet';
    9. $html = file_get_html($page_adress);
    10.  
    11. if (!$connect_db) {
    12.     die('Ошибка подключения: ' . mysql_error());
    13. } else {
    14. echo 'Succes connect';
    15. }
    16.  
    17. if(count($html->find('div.b-catalog__item')))
    18. {
    19. foreach($html->find('p.b-catalog__item__sku a') as $article)
    20. foreach($html->find('p.b-catalog__item__t a') as $partname)
    21. mysql_query("
    22.     INSERT INTO `parts_temp` (`tb_parts_name`, `tb_parts_code`, 'tb_cars_manufacture', 'tb_cars_model')
    23.         VALUES ('{$partname->innertext}', '{$article->innertext}', '{$car}', '{$model}')");
    24. }
    25. ?>
    Собственно, если требуется записать только переменные $article и $partname, то все нормально, а добавил $car и $model, ничего в БД не пишет. Помогите, пожалуйста, разобраться. Спасибо.
     
  2. metadon

    metadon Активный пользователь

    С нами с:
    6 фев 2006
    Сообщения:
    779
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Попробуй тот sql запрос который не работает проверить в phpmyadmin и посмотреть будет ли ошибка.
     
  3. sharunm

    sharunm Активный пользователь

    С нами с:
    16 ноя 2014
    Сообщения:
    58
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Все-то работает, проблема, думаю, в том, что переменные $partname и $article внутри массива. В общем, код ниже не распознает значение переменных $car и $model
    Код (Text):
    1.  
    2. VALUES ('{$partname->innertext}', '{$article->innertext}', '{$car}', '{$model}')");
    Вот у меня и, по сути, вопрос, как запихнуть значения этих переменных или в массив или в таблицу сразу. Может, посчитать количество элементов, например, $article, создать для массива $html новый элемент, этому элементу присвоить значение, например, переменной $car, а потом записать столько раз, сколько записей $article. Вот, только я начинающий, мне сложновато это пока. Может есть другой способ решения задачи?
     
  4. metadon

    metadon Активный пользователь

    С нами с:
    6 фев 2006
    Сообщения:
    779
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    http://phpfaq.ru/debug Отладка и поиск ошибок в своем алгоритме
     
  5. sharunm

    sharunm Активный пользователь

    С нами с:
    16 ноя 2014
    Сообщения:
    58
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Вообще, мой код в корне не верен, т.к. на странице в 60 пар элементов (артикул и наименование) он выводит каждый элемент с каждым, т.не. в итоге мы получаем 3600 записей. Поэтому просьба, помогите разобраться с кодом так, чтобы в итоге это было 60 записей Артикул + Наименование + Марка + Модель.
     
  6. metadon

    metadon Активный пользователь

    С нами с:
    6 фев 2006
    Сообщения:
    779
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Так в чём проблема, что конкретно не знаешь как сделать?
     
  7. sharunm

    sharunm Активный пользователь

    С нами с:
    16 ноя 2014
    Сообщения:
    58
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Именно в этом и проблема, что я не знаю, как это написать, все хрень какая-то выходит, по-разному пробую. Вот и прошу, чтобы хоть кто-то подсказал, как это написать (кодик бы примерно), а я бы разобрался уже, почему это работает.
     
  8. metadon

    metadon Активный пользователь

    С нами с:
    6 фев 2006
    Сообщения:
    779
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Что конкретно у тебя не выходит?
    Вот ты сел за компьютер и дальше что? Где стопор происходит, может мышкой не умеешь пользоваться, мы не знаем.
    Что написать не знаешь как? Что за хрень выходит? Зачем по разному пробовать если можно алгоритм составить в голове и на листике и перенести в код.
    Вот весь текст что ты тут написал в теме, если бы тебе поставили задачу понять из твоего поста, ты бы понял? Или нужны были уточнения?
     
  9. sharunm

    sharunm Активный пользователь

    С нами с:
    16 ноя 2014
    Сообщения:
    58
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Я напишу, сейчас кое-что дошло, хотя есть косячок. ) Моментик, чуть позже напишу

    Добавлено спустя 9 минут 42 секунды:
    Re: Пишу простенький парсер. Проблема с записью результатов в БД
    Вот, переписал код. Взял в качестве примера страницу "http://relines.ru/catalog/chery-amulet/", т.к. здесь проще выдергивать артикулы и наименования. На экран через echo все выводит, единственное, в конце почему-то к списку добавляет ниже добавляет значения переменных $car и $model, а вот в БД не пишет при этом.

    А задача простая пока: взять артикулы и наименования и записать их в БД, а еще с каждой записью в отдельные столбцы записать марку и модель.

    Код (Text):
    1.  
    2. <?php
    3. // example of how to use advanced selector features
    4. include('../config.php');
    5. include('../simple_html_dom.php');
    6. $html = file_get_html('http://relines.ru/catalog/chery-amulet/');
    7. $count_pars = count ($html->find('p.b-catalog__item__sku a'));
    8. $car='CHERY';
    9. $model="Amulet";
    10. echo 'it works <br/>'.$count_pars.'<br/>';
    11.  
    12. $element_article=$html->find('p.b-catalog__item__sku a');
    13. $element_name=$html->find('p.b-catalog__item__t a');
    14.  
    15.  
    16. for($i = 0; $i <= $count_pars; $i++)
    17.   {
    18.      echo $element_article[$i]->innertext.'#'. $element_name[$i]->innertext.'#'.$car.'#'.$model.'<br/>';
    19.  
    20. mysql_query("
    21.     INSERT INTO `parts_temp` (`tb_parts_name`, `tb_parts_code`,'tb_cars_manufacture', 'tb_cars_model')
    22.         VALUES ('{$element_name[$i]->innertext}', '{$element_article[$i]->innertext}, {$car}, {$model}')");
    23.   }
    24.  
    25. ?>
    Добавлено спустя 6 минут 31 секунду:
    Re: Пишу простенький парсер. Проблема с записью результатов в БД
    Вот адрес страницы
    http://pars1.svdmag.ru/mylessons/count.php
    А это config.php
    Код (Text):
    1. <?
    2. $sdb_name = "localhost";
    3. $user_name = "imagmeberu_pars";
    4. $user_password = "123qweznoxiu";
    5. $db_name = "imagmeberu_pars";
    6.  
    7. $connect_db = mysql_connect($sdb_name, $user_name, $user_password) or die(mysql_error());
    8. mysql_select_db($db_name) or die(mysql_error());
    9. mysql_set_charset("utf8");
    10.  
    11.  
    12. ?>
    А это библиотека DOM
    Код (Text):
    1.  
    2. <?php
    3. /**
    4.  * Website: http://sourceforge.net/projects/simplehtmldom/
    5.  * Acknowledge: Jose Solorzano (https://sourceforge.net/projects/php-html/)
    6.  * Contributions by:
    7.  *     Yousuke Kumakura (Attribute filters)
    8.  *     Vadim Voituk (Negative indexes supports of "find" method)
    9.  *     Antcs (Constructor with automatically load contents either text or file/url)
    10.  *
    11.  * all affected sections have comments starting with "PaperG"
    12.  *
    13.  * Paperg - Added case insensitive testing of the value of the selector.
    14.  * Paperg - Added tag_start for the starting index of tags - NOTE: This works but not accurately.
    15.  *  This tag_start gets counted AFTER \r\n have been crushed out, and after the remove_noice calls so it will not reflect the REAL position of the tag in the source,
    16.  *  it will almost always be smaller by some amount.
    17.  *  We use this to determine how far into the file the tag in question is.  This "percentage will never be accurate as the $dom->size is the "real" number of bytes the dom was created from.
    18.  *  but for most purposes, it's a really good estimation.
    19.  * Paperg - Added the forceTagsClosed to the dom constructor.  Forcing tags closed is great for malformed html, but it CAN lead to parsing errors.
    20.  * Allow the user to tell us how much they trust the html.
    21.  * Paperg add the text and plaintext to the selectors for the find syntax.  plaintext implies text in the innertext of a node.  text implies that the tag is a text node.
    22.  * This allows for us to find tags based on the text they contain.
    23.  * Create find_ancestor_tag to see if a tag is - at any level - inside of another specific tag.
    24.  * Paperg: added parse_charset so that we know about the character set of the source document.
    25.  *  NOTE:  If the user's system has a routine called get_last_retrieve_url_contents_content_type availalbe, we will assume it's returning the content-type header from the
    26.  *  last transfer or curl_exec, and we will parse that and use it in preference to any other method of charset detection.
    27.  *
    28.  * Licensed under The MIT License
    29.  * Redistributions of files must retain the above copyright notice.
    30.  *
    31.  * @author S.C. Chen <me578022@gmail.com>
    32.  * @author John Schlick
    33.  * @author Rus Carroll
    34.  * @version 1.11 ($Rev: 184 $)
    35.  * @package PlaceLocalInclude
    36.  * @subpackage simple_html_dom
    37.  */
    38.  
    39. /**
    40.  * All of the Defines for the classes below.
    41.  * @author S.C. Chen <me578022@gmail.com>
    42.  */
    43. define('HDOM_TYPE_ELEMENT', 1);
    44. define('HDOM_TYPE_COMMENT', 2);
    45. define('HDOM_TYPE_TEXT',    3);
    46. define('HDOM_TYPE_ENDTAG',  4);
    47. define('HDOM_TYPE_ROOT',    5);
    48. define('HDOM_TYPE_UNKNOWN', 6);
    49. define('HDOM_QUOTE_DOUBLE', 0);
    50. define('HDOM_QUOTE_SINGLE', 1);
    51. define('HDOM_QUOTE_NO',     3);
    52. define('HDOM_INFO_BEGIN',   0);
    53. define('HDOM_INFO_END',     1);
    54. define('HDOM_INFO_QUOTE',   2);
    55. define('HDOM_INFO_SPACE',   3);
    56. define('HDOM_INFO_TEXT',    4);
    57. define('HDOM_INFO_INNER',   5);
    58. define('HDOM_INFO_OUTER',   6);
    59. define('HDOM_INFO_ENDSPACE',7);
    60. define('DEFAULT_TARGET_CHARSET', 'UTF-8');
    61. define('DEFAULT_BR_TEXT', "\r\n");
    62. // helper functions
    63. // -----------------------------------------------------------------------------
    64. // get html dom from file
    65. // $maxlen is defined in the code as PHP_STREAM_COPY_ALL which is defined as -1.
    66. function file_get_html($url, $use_include_path = false, $context=null, $offset = -1, $maxLen=-1, $lowercase = true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT)
    67. {
    68.     // We DO force the tags to be terminated.
    69.     $dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $defaultBRText);
    70.     // For sourceforge users: uncomment the next line and comment the retreive_url_contents line 2 lines down if it is not already done.
    71.     $contents = file_get_contents($url, $use_include_path, $context, $offset);
    72.     // Paperg - use our own mechanism for getting the contents as we want to control the timeout.
    73. //    $contents = retrieve_url_contents($url);
    74.     if (empty($contents))
    75.     {
    76.         return false;
    77.     }
    78.     // The second parameter can force the selectors to all be lowercase.
    79.     $dom->load($contents, $lowercase, $stripRN);
    80.     return $dom;
    81. }
    82.  
    83. // get html dom from string
    84. function str_get_html($str, $lowercase=true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT)
    85. {
    86.     $dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $defaultBRText);
    87.     if (empty($str))
    88.     {
    89.         $dom->clear();
    90.         return false;
    91.     }
    92.     $dom->load($str, $lowercase, $stripRN);
    93.     return $dom;
    94. }
    95.  
    96. // dump html dom tree
    97. function dump_html_tree($node, $show_attr=true, $deep=0)
    98. {
    99.     $node->dump($node);
    100. }
    101.  
    102. /**
    103.  * simple html dom node
    104.  * PaperG - added ability for "find" routine to lowercase the value of the selector.
    105.  * PaperG - added $tag_start to track the start position of the tag in the total byte index
    106.  *
    107.  * @package PlaceLocalInclude
    108.  */
    109. class simple_html_dom_node {
    110.     public $nodetype = HDOM_TYPE_TEXT;
    111.     public $tag = 'text';
    112.     public $attr = array();
    113.     public $children = array();
    114.     public $nodes = array();
    115.     public $parent = null;
    116.     public $_ = array();
    117.     public $tag_start = 0;
    118.     private $dom = null;
    119.  
    120.     function __construct($dom)
    121.     {
    122.         $this->dom = $dom;
    123.         $dom->nodes[] = $this;
    124.     }
    125.  
    126.     function __destruct()
    127.     {
    128.         $this->clear();
    129.     }
    130.  
    131.     function __toString()
    132.     {
    133.         return $this->outertext();
    134.     }
    135.  
    136.     // clean up memory due to php5 circular references memory leak...
    137.     function clear()
    138.     {
    139.         $this->dom = null;
    140.         $this->nodes = null;
    141.         $this->parent = null;
    142.         $this->children = null;
    143.     }
    144.  
    145.     // dump node's tree
    146.     function dump($show_attr=true, $deep=0)
    147.     {
    148.         $lead = str_repeat('    ', $deep);
    149.  
    150.         echo $lead.$this->tag;
    151.         if ($show_attr && count($this->attr)>0)
    152.         {
    153.             echo '(';
    154.             foreach ($this->attr as $k=>$v)
    155.                 echo "[$k]=>\"".$this->$k.'", ';
    156.             echo ')';
    157.         }
    158.         echo "\n";
    159.  
    160.         foreach ($this->nodes as $c)
    161.             $c->dump($show_attr, $deep+1);
    162.     }
    163.  
    164.  
    165.     // Debugging function to dump a single dom node with a bunch of information about it.
    166.     function dump_node()
    167.     {
    168.         echo $this->tag;
    169.         if (count($this->attr)>0)
    170.         {
    171.             echo '(';
    172.             foreach ($this->attr as $k=>$v)
    173.             {
    174.                 echo "[$k]=>\"".$this->$k.'", ';
    175.             }
    176.             echo ')';
    177.         }
    178.         if (count($this->attr)>0)
    179.         {
    180.             echo ' $_ (';
    181.             foreach ($this->_ as $k=>$v)
    182.             {
    183.                 if (is_array($v))
    184.                 {
    185.                     echo "[$k]=>(";
    186.                     foreach ($v as $k2=>$v2)
    187.                     {
    188.                         echo "[$k2]=>\"".$v2.'", ';
    189.                     }
    190.                     echo ")";
    191.                 } else {
    192.                     echo "[$k]=>\"".$v.'", ';
    193.                 }
    194.             }
    195.             echo ")";
    196.         }
    197.  
    198.         if (isset($this->text))
    199.         {
    200.             echo " text: (" . $this->text . ")";
    201.         }
    202.  
    203.         echo " children: " . count($this->children);
    204.         echo " nodes: " . count($this->nodes);
    205.         echo " tag_start: " . $this->tag_start;
    206.         echo "\n";
    207.  
    208.     }
    209.  
    210.     // returns the parent of node
    211.     function parent()
    212.     {
    213.         return $this->parent;
    214.     }
    215.  
    216.     // returns children of node
    217.     function children($idx=-1)
    218.     {
    219.         if ($idx===-1) return $this->children;
    220.         if (isset($this->children[$idx])) return $this->children[$idx];
    221.         return null;
    222.     }
    223.  
    224.     // returns the first child of node
    225.     function first_child()
    226.     {
    227.         if (count($this->children)>0) return $this->children[0];
    228.         return null;
    229.     }
    230.  
    231.     // returns the last child of node
    232.     function last_child()
    233.     {
    234.         if (($count=count($this->children))>0) return $this->children[$count-1];
    235.         return null;
    236.     }
    237.  
    238.     // returns the next sibling of node
    239.     function next_sibling()
    240.     {
    241.         if ($this->parent===null) return null;
    242.         $idx = 0;
    243.         $count = count($this->parent->children);
    244.         while ($idx<$count && $this!==$this->parent->children[$idx])
    245.             ++$idx;
    246.         if (++$idx>=$count) return null;
    247.         return $this->parent->children[$idx];
    248.     }
    249.  
    250.     // returns the previous sibling of node
    251.     function prev_sibling()
    252.     {
    253.         if ($this->parent===null) return null;
    254.         $idx = 0;
    255.         $count = count($this->parent->children);
    256.         while ($idx<$count && $this!==$this->parent->children[$idx])
    257.             ++$idx;
    258.         if (--$idx<0) return null;
    259.         return $this->parent->children[$idx];
    260.     }
    261.  
    262.     // function to locate a specific ancestor tag in the path to the root.
    263.     function find_ancestor_tag($tag)
    264.     {
    265.         global $debugObject;
    266.         if (is_object($debugObject))
    267.         {
    268.             $debugObject->debugLogEntry(1);
    269.         }
    270.  
    271.         // Start by including ourselves in the comparison.
    272.         $returnDom = $this;
    273.  
    274.         while (!is_null($returnDom))
    275.         {
    276.             if (is_object($debugObject))
    277.             {
    278.                 $debugObject->debugLog(2, "Current tag is: " . $returnDom->tag);
    279.             }
    280.  
    281.             if ($returnDom->tag == $tag)
    282.             {
    283.                 break;
    284.             }
    285.             $returnDom = $returnDom->parent;
    286.         }
    287.         return $returnDom;
    288.     }
    289.  
    290.     // get dom node's inner html
    291.     function innertext()
    292.     {
    293.         if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
    294.         if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
    295.  
    296.         $ret = '';
    297.         foreach ($this->nodes as $n)
    298.             $ret .= $n->outertext();
    299.         return $ret;
    300.     }
    301.  
    302.     // get dom node's outer text (with tag)
    303.     function outertext()
    304.     {
    305.         global $debugObject;
    306.         if (is_object($debugObject))
    307.         {
    308.             $text = '';
    309.             if ($this->tag == 'text')
    310.             {
    311.                 if (!empty($this->text))
    312.                 {
    313.                     $text = " with text: " . $this->text;
    314.                 }
    315.             }
    316.             $debugObject->debugLog(1, 'Innertext of tag: ' . $this->tag . $text);
    317.         }
    318.  
    319.         if ($this->tag==='root') return $this->innertext();
    320.  
    321.         // trigger callback
    322.         if ($this->dom && $this->dom->callback!==null)
    323.         {
    324.             call_user_func_array($this->dom->callback, array($this));
    325.         }
    326.  
    327.         if (isset($this->_[HDOM_INFO_OUTER])) return $this->_[HDOM_INFO_OUTER];
    328.         if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
    329.  
    330.         // render begin tag
    331.         if ($this->dom && $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]])
    332.         {
    333.             $ret = $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]->makeup();
    334.         } else {
    335.             $ret = "";
    336.         }
    337.  
    338.         // render inner text
    339.         if (isset($this->_[HDOM_INFO_INNER]))
    340.         {
    341.             // If it's a br tag...  don't return the HDOM_INNER_INFO that we may or may not have added.
    342.             if ($this->tag != "br")
    343.             {
    344.                 $ret .= $this->_[HDOM_INFO_INNER];
    345.             }
    346.         } else {
    347.             if ($this->nodes)
    348.             {
    349.                 foreach ($this->nodes as $n)
    350.                 {
    351.                     $ret .= $this->convert_text($n->outertext());
    352.                 }
    353.             }
    354.         }
    355.  
    356.         // render end tag
    357.         if (isset($this->_[HDOM_INFO_END]) && $this->_[HDOM_INFO_END]!=0)
    358.             $ret .= '</'.$this->tag.'>';
    359.         return $ret;
    360.     }
    361.  
    362.     // get dom node's plain text
    363.     function text()
    364.     {
    365.         if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
    366.         switch ($this->nodetype)
    367.         {
    368.             case HDOM_TYPE_TEXT: return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
    369.             case HDOM_TYPE_COMMENT: return '';
    370.             case HDOM_TYPE_UNKNOWN: return '';
    371.         }
    372.         if (strcasecmp($this->tag, 'script')===0) return '';
    373.         if (strcasecmp($this->tag, 'style')===0) return '';
    374.  
    375.         $ret = '';
    376.         // In rare cases, (always node type 1 or HDOM_TYPE_ELEMENT - observed for some span tags, and some p tags) $this->nodes is set to NULL.
    377.         // NOTE: This indicates that there is a problem where it's set to NULL without a clear happening.
    378.         // WHY is this happening?
    379.         if (!is_null($this->nodes))
    380.         {
    381.             foreach ($this->nodes as $n)
    382.             {
    383.                 $ret .= $this->convert_text($n->text());
    384.             }
    385.         }
    386.         return $ret;
    387.     }
    388.  
    389.     function xmltext()
    390.     {
    391.         $ret = $this->innertext();
    392.         $ret = str_ireplace('<![CDATA[', '', $ret);
    393.         $ret = str_replace(']]>', '', $ret);
    394.         return $ret;
    395.     }
    396.  
    397.     // build node's text with tag
    398.     function makeup()
    399.     {
    400.         // text, comment, unknown
    401.         if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
    402.  
    403.         $ret = '<'.$this->tag;
    404.         $i = -1;
    405.  
    406.         foreach ($this->attr as $key=>$val)
    407.         {
    408.             ++$i;
    409.  
    410.             // skip removed attribute
    411.             if ($val===null || $val===false)
    412.                 continue;
    413.  
    414.             $ret .= $this->_[HDOM_INFO_SPACE][$i][0];
    415.             //no value attr: nowrap, checked selected...
    416.             if ($val===true)
    417.                 $ret .= $key;
    418.             else {
    419.                 switch ($this->_[HDOM_INFO_QUOTE][$i])
    420.                 {
    421.                     case HDOM_QUOTE_DOUBLE: $quote = '"'; break;
    422.                     case HDOM_QUOTE_SINGLE: $quote = '\''; break;
    423.                     default: $quote = '';
    424.                 }
    425.                 $ret .= $key.$this->_[HDOM_INFO_SPACE][$i][1].'='.$this->_[HDOM_INFO_SPACE][$i][2].$quote.$val.$quote;
    426.             }
    427.         }
    428.         $ret = $this->dom->restore_noise($ret);
    429.         return $ret . $this->_[HDOM_INFO_ENDSPACE] . '>';
    430.     }
    431.  
    432.     // find elements by css selector
    433.     //PaperG - added ability for find to lowercase the value of the selector.
    434.     function find($selector, $idx=null, $lowercase=false)
    435.     {
    436.         $selectors = $this->parse_selector($selector);
    437.         if (($count=count($selectors))===0) return array();
    438.         $found_keys = array();
    439.  
    440.         // find each selector
    441.         for ($c=0; $c<$count; ++$c)
    442.         {
    443.             // The change on the below line was documented on the sourceforge code tracker id 2788009
    444.             // used to be: if (($levle=count($selectors[0]))===0) return array();
    445.             if (($levle=count($selectors[$c]))===0) return array();
    446.             if (!isset($this->_[HDOM_INFO_BEGIN])) return array();
    447.  
    448.             $head = array($this->_[HDOM_INFO_BEGIN]=>1);
    449.  
    450.             // handle descendant selectors, no recursive!
    451.             for ($l=0; $l<$levle; ++$l)
    452.             {
    453.                 $ret = array();
    454.                 foreach ($head as $k=>$v)
    455.                 {
    456.                     $n = ($k===-1) ? $this->dom->root : $this->dom->nodes[$k];
    457.                     //PaperG - Pass this optional parameter on to the seek function.
    458.                     $n->seek($selectors[$c][$l], $ret, $lowercase);
    459.                 }
    460.                 $head = $ret;
    461.             }
    462.  
    463.             foreach ($head as $k=>$v)
    464.             {
    465.                 if (!isset($found_keys[$k]))
    466.                     $found_keys[$k] = 1;
    467.             }
    468.         }
    469.  
    470.         // sort keys
    471.         ksort($found_keys);
    472.  
    473.         $found = array();
    474.         foreach ($found_keys as $k=>$v)
    475.             $found[] = $this->dom->nodes[$k];
    476.  
    477.         // return nth-element or array
    478.         if (is_null($idx)) return $found;
    479.         else if ($idx<0) $idx = count($found) + $idx;
    480.         return (isset($found[$idx])) ? $found[$idx] : null;
    481.     }
    482.  
    483.     // seek for given conditions
    484.     // PaperG - added parameter to allow for case insensitive testing of the value of a selector.
    485.     protected function seek($selector, &$ret, $lowercase=false)
    486.     {
    487.         global $debugObject;
    488.         if (is_object($debugObject))
    489.         {
    490.             $debugObject->debugLogEntry(1);
    491.         }
    492.  
    493.         list($tag, $key, $val, $exp, $no_key) = $selector;
    494.  
    495.         // xpath index
    496.         if ($tag && $key && is_numeric($key))
    497.         {
    498.             $count = 0;
    499.             foreach ($this->children as $c)
    500.             {
    501.                 if ($tag==='*' || $tag===$c->tag) {
    502.                     if (++$count==$key) {
    503.                         $ret[$c->_[HDOM_INFO_BEGIN]] = 1;
    504.                         return;
    505.                     }
    506.                 }
    507.             }
    508.             return;
    509.         }
    510.  
    511.         $end = (!empty($this->_[HDOM_INFO_END])) ? $this->_[HDOM_INFO_END] : 0;
    512.         if ($end==0) {
    513.             $parent = $this->parent;
    514.             while (!isset($parent->_[HDOM_INFO_END]) && $parent!==null) {
    515.                 $end -= 1;
    516.                 $parent = $parent->parent;
    517.             }
    518.             $end += $parent->_[HDOM_INFO_END];
    519.         }
    520.  
    521.         for ($i=$this->_[HDOM_INFO_BEGIN]+1; $i<$end; ++$i) {
    522.             $node = $this->dom->nodes[$i];
    523.  
    524.             $pass = true;
    525.  
    526.             if ($tag==='*' && !$key) {
    527.                 if (in_array($node, $this->children, true))
    528.                     $ret[$i] = 1;
    529.                 continue;
    530.             }
    531.  
    532.             // compare tag
    533.             if ($tag && $tag!=$node->tag && $tag!=='*') {$pass=false;}
    534.             // compare key
    535.             if ($pass && $key) {
    536.                 if ($no_key) {
    537.                     if (isset($node->attr[$key])) $pass=false;
    538.                 } else {
    539.                     if (($key != "plaintext") && !isset($node->attr[$key])) $pass=false;
    540.                 }
    541.             }
    542.             // compare value
    543.             if ($pass && $key && $val  && $val!=='*') {
    544.                 // If they have told us that this is a "plaintext" search then we want the plaintext of the node - right?
    545.                 if ($key == "plaintext") {
    546.                     // $node->plaintext actually returns $node->text();
    547.                     $nodeKeyValue = $node->text();
    548.                 } else {
    549.                     // this is a normal search, we want the value of that attribute of the tag.
    550.                     $nodeKeyValue = $node->attr[$key];
    551.                 }
    552.                 if (is_object($debugObject)) {$debugObject->debugLog(2, "testing node: " . $node->tag . " for attribute: " . $key . $exp . $val . " where nodes value is: " . $nodeKeyValue);}
    553.  
    554.                 //PaperG - If lowercase is set, do a case insensitive test of the value of the selector.
    555.                 if ($lowercase) {
    556.                     $check = $this->match($exp, strtolower($val), strtolower($nodeKeyValue));
    557.                 } else {
    558.                     $check = $this->match($exp, $val, $nodeKeyValue);
    559.                 }
    560.                 if (is_object($debugObject)) {$debugObject->debugLog(2, "after match: " . ($check ? "true" : "false"));}
    561.  
    562.                 // handle multiple class
    563.                 if (!$check && strcasecmp($key, 'class')===0) {
    564.                     foreach (explode(' ',$node->attr[$key]) as $k) {
    565.                         // Without this, there were cases where leading, trailing, or double spaces lead to our comparing blanks - bad form.
    566.                         if (!empty($k)) {
    567.                             if ($lowercase) {
    568.                                 $check = $this->match($exp, strtolower($val), strtolower($k));
    569.                             } else {
    570.                                 $check = $this->match($exp, $val, $k);
    571.                             }
    572.                             if ($check) break;
    573.                         }
    574.                     }
    575.                 }
    576.                 if (!$check) $pass = false;
    577.             }
    578.             if ($pass) $ret[$i] = 1;
    579.             unset($node);
    580.         }
    581.         // It's passed by reference so this is actually what this function returns.
    582.         if (is_object($debugObject)) {$debugObject->debugLog(1, "EXIT - ret: ", $ret);}
    583.     }
    584.  
    585.     protected function match($exp, $pattern, $value) {
    586.         global $debugObject;
    587.         if (is_object($debugObject)) {$debugObject->debugLogEntry(1);}
    588.  
    589.         switch ($exp) {
    590.             case '=':
    591.                 return ($value===$pattern);
    592.             case '!=':
    593.                 return ($value!==$pattern);
    594.             case '^=':
    595.                 return preg_match("/^".preg_quote($pattern,'/')."/", $value);
    596.             case '$=':
    597.                 return preg_match("/".preg_quote($pattern,'/')."$/", $value);
    598.             case '*=':
    599.                 if ($pattern[0]=='/') {
    600.                     return preg_match($pattern, $value);
    601.                 }
    602.                 return preg_match("/".$pattern."/i", $value);
    603.         }
    604.         return false;
    605.     }
    606.  
    607.     protected function parse_selector($selector_string) {
    608.         global $debugObject;
    609.         if (is_object($debugObject)) {$debugObject->debugLogEntry(1);}
    610.  
    611.         // pattern of CSS selectors, modified from mootools
    612.         // Paperg: Add the colon to the attrbute, so that it properly finds <tag attr:ibute="something" > like google does.
    613.         // Note: if you try to look at this attribute, yo MUST use getAttribute since $dom->x:y will fail the php syntax check.
    614. // Notice the \[ starting the attbute?  and the @? following?  This implies that an attribute can begin with an @ sign that is not captured.
    615. // This implies that an html attribute specifier may start with an @ sign that is NOT captured by the expression.
    616. // farther study is required to determine of this should be documented or removed.
    617. //        $pattern = "/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is";
    618.         $pattern = "/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-:]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is";
    619.         preg_match_all($pattern, trim($selector_string).' ', $matches, PREG_SET_ORDER);
    620.         if (is_object($debugObject)) {$debugObject->debugLog(2, "Matches Array: ", $matches);}
    621.  
    622.         $selectors = array();
    623.         $result = array();
    624.         //print_r($matches);
    625.  
    626.         foreach ($matches as $m) {
    627.             $m[0] = trim($m[0]);
    628.             if ($m[0]==='' || $m[0]==='/' || $m[0]==='//') continue;
    629.             // for browser generated xpath
    630.             if ($m[1]==='tbody') continue;
    631.  
    632.             list($tag, $key, $val, $exp, $no_key) = array($m[1], null, null, '=', false);
    633.             if (!empty($m[2])) {$key='id'; $val=$m[2];}
    634.             if (!empty($m[3])) {$key='class'; $val=$m[3];}
    635.             if (!empty($m[4])) {$key=$m[4];}
    636.             if (!empty($m[5])) {$exp=$m[5];}
    637.             if (!empty($m[6])) {$val=$m[6];}
    638.  
    639.             // convert to lowercase
    640.             if ($this->dom->lowercase) {$tag=strtolower($tag); $key=strtolower($key);}
    641.             //elements that do NOT have the specified attribute
    642.             if (isset($key[0]) && $key[0]==='!') {$key=substr($key, 1); $no_key=true;}
    643.  
    644.             $result[] = array($tag, $key, $val, $exp, $no_key);
    645.             if (trim($m[7])===',') {
    646.                 $selectors[] = $result;
    647.                 $result = array();
    648.             }
    649.         }
    650.         if (count($result)>0)
    651.             $selectors[] = $result;
    652.         return $selectors;
    653.     }
    654.  
    655.     function __get($name) {
    656.         if (isset($this->attr[$name]))
    657.         {
    658.             return $this->convert_text($this->attr[$name]);
    659.         }
    660.         switch ($name) {
    661.             case 'outertext': return $this->outertext();
    662.             case 'innertext': return $this->innertext();
    663.             case 'plaintext': return $this->text();
    664.             case 'xmltext': return $this->xmltext();
    665.             default: return array_key_exists($name, $this->attr);
    666.         }
    667.     }
    668.  
    669.     function __set($name, $value) {
    670.         switch ($name) {
    671.             case 'outertext': return $this->_[HDOM_INFO_OUTER] = $value;
    672.             case 'innertext':
    673.                 if (isset($this->_[HDOM_INFO_TEXT])) return $this->_[HDOM_INFO_TEXT] = $value;
    674.                 return $this->_[HDOM_INFO_INNER] = $value;
    675.         }
    676.         if (!isset($this->attr[$name])) {
    677.             $this->_[HDOM_INFO_SPACE][] = array(' ', '', '');
    678.             $this->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE;
    679.         }
    680.         $this->attr[$name] = $value;
    681.     }
    682.  
    683.     function __isset($name) {
    684.         switch ($name) {
    685.             case 'outertext': return true;
    686.             case 'innertext': return true;
    687.             case 'plaintext': return true;
    688.         }
    689.         //no value attr: nowrap, checked selected...
    690.         return (array_key_exists($name, $this->attr)) ? true : isset($this->attr[$name]);
    691.     }
    692.  
    693.     function __unset($name) {
    694.         if (isset($this->attr[$name]))
    695.             unset($this->attr[$name]);
    696.     }
    697.  
    698.     // PaperG - Function to convert the text from one character set to another if the two sets are not the same.
    699.     function convert_text($text) {
    700.         global $debugObject;
    701.         if (is_object($debugObject)) {$debugObject->debugLogEntry(1);}
    702.  
    703.         $converted_text = $text;
    704.  
    705.         $sourceCharset = "";
    706.         $targetCharset = "";
    707.         if ($this->dom) {
    708.             $sourceCharset = strtoupper($this->dom->_charset);
    709.             $targetCharset = strtoupper($this->dom->_target_charset);
    710.         }
    711.         if (is_object($debugObject)) {$debugObject->debugLog(3, "source charset: " . $sourceCharset . " target charaset: " . $targetCharset);}
    712.  
    713.         if (!empty($sourceCharset) && !empty($targetCharset) && (strcasecmp($sourceCharset, $targetCharset) != 0))
    714.         {
    715.             // Check if the reported encoding could have been incorrect and the text is actually already UTF-8
    716.             if ((strcasecmp($targetCharset, 'UTF-8') == 0) && ($this->is_utf8($text)))
    717.             {
    718.                 $converted_text = $text;
    719.             }
    720.             else
    721.             {
    722.                 $converted_text = iconv($sourceCharset, $targetCharset, $text);
    723.             }
    724.         }
    725.  
    726.         return $converted_text;
    727.     }
    728.  
    729.     function is_utf8($string)
    730.     {
    731.         return (utf8_encode(utf8_decode($string)) == $string);
    732.     }
    733.  
    734.     // camel naming conventions
    735.     function getAllAttributes() {return $this->attr;}
    736.     function getAttribute($name) {return $this->__get($name);}
    737.     function setAttribute($name, $value) {$this->__set($name, $value);}
    738.     function hasAttribute($name) {return $this->__isset($name);}
    739.     function removeAttribute($name) {$this->__set($name, null);}
    740.     function getElementById($id) {return $this->find("#$id", 0);}
    741.     function getElementsById($id, $idx=null) {return $this->find("#$id", $idx);}
    742.     function getElementByTagName($name) {return $this->find($name, 0);}
    743.     function getElementsByTagName($name, $idx=null) {return $this->find($name, $idx);}
    744.     function parentNode() {return $this->parent();}
    745.     function childNodes($idx=-1) {return $this->children($idx);}
    746.     function firstChild() {return $this->first_child();}
    747.     function lastChild() {return $this->last_child();}
    748.     function nextSibling() {return $this->next_sibling();}
    749.     function previousSibling() {return $this->prev_sibling();}
    750. }
    751.  
    752. /**
    753.  * simple html dom parser
    754.  * Paperg - in the find routine: allow us to specify that we want case insensitive testing of the value of the selector.
    755.  * Paperg - change $size from protected to public so we can easily access it
    756.  * Paperg - added ForceTagsClosed in the constructor which tells us whether we trust the html or not.  Default is to NOT trust it.
    757.  *
    758.  * @package PlaceLocalInclude
    759.  */
    760. class simple_html_dom {
    761.     public $root = null;
    762.     public $nodes = array();
    763.     public $callback = null;
    764.     public $lowercase = false;
    765.     public $size;
    766.     protected $pos;
    767.     protected $doc;
    768.     protected $char;
    769.     protected $cursor;
    770.     protected $parent;
    771.     protected $noise = array();
    772.     protected $token_blank = " \t\r\n";
    773.     protected $token_equal = ' =/>';
    774.     protected $token_slash = " />\r\n\t";
    775.     protected $token_attr = ' >';
    776.     protected $_charset = '';
    777.     protected $_target_charset = '';
    778.     protected $default_br_text = "";
    779.  
    780.     // use isset instead of in_array, performance boost about 30%...
    781.     protected $self_closing_tags = array('img'=>1, 'br'=>1, 'input'=>1, 'meta'=>1, 'link'=>1, 'hr'=>1, 'base'=>1, 'embed'=>1, 'spacer'=>1);
    782.     protected $block_tags = array('root'=>1, 'body'=>1, 'form'=>1, 'div'=>1, 'span'=>1, 'table'=>1);
    783.     // Known sourceforge issue #2977341
    784.     // B tags that are not closed cause us to return everything to the end of the document.
    785.     protected $optional_closing_tags = array(
    786.         'tr'=>array('tr'=>1, 'td'=>1, 'th'=>1),
    787.         'th'=>array('th'=>1),
    788.         'td'=>array('td'=>1),
    789.         'li'=>array('li'=>1),
    790.         'dt'=>array('dt'=>1, 'dd'=>1),
    791.         'dd'=>array('dd'=>1, 'dt'=>1),
    792.         'dl'=>array('dd'=>1, 'dt'=>1),
    793.         'p'=>array('p'=>1),
    794.         'nobr'=>array('nobr'=>1),
    795.         'b'=>array('b'=>1),
    796.     );
    797.  
    798.     function __construct($str=null, $lowercase=true, $forceTagsClosed=true, $target_charset=DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT) {
    799.         if ($str) {
    800.             if (preg_match("/^http:\/\//i",$str) || is_file($str))
    801.                 $this->load_file($str);
    802.             else
    803.                 $this->load($str, $lowercase, $stripRN, $defaultBRText);
    804.         }
    805.         // Forcing tags to be closed implies that we don't trust the html, but it can lead to parsing errors if we SHOULD trust the html.
    806.         if (!$forceTagsClosed) {
    807.             $this->optional_closing_array=array();
    808.         }
    809.         $this->_target_charset = $target_charset;
    810.     }
    811.  
    812.     function __destruct() {
    813.         $this->clear();
    814.     }
    815.  
    816.     // load html from string
    817.     function load($str, $lowercase=true, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT) {
    818.         global $debugObject;
    819.  
    820.         // prepare
    821.         $this->prepare($str, $lowercase, $stripRN, $defaultBRText);
    822.         // strip out comments
    823.         $this->remove_noise("'<!--(.*?)-->'is");
    824.         // strip out cdata
    825.         $this->remove_noise("'<!\[CDATA\[(.*?)\]\]>'is", true);
    826.         // Per sourceforge http://sourceforge.net/tracker/?func=detail&aid=2949097&group_id=218559&atid=1044037
    827.         // Script tags removal now preceeds style tag removal.
    828.         // strip out <script> tags
    829.         $this->remove_noise("'<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>'is");
    830.         $this->remove_noise("'<\s*script\s*>(.*?)<\s*/\s*script\s*>'is");
    831.         // strip out <style> tags
    832.         $this->remove_noise("'<\s*style[^>]*[^/]>(.*?)<\s*/\s*style\s*>'is");
    833.         $this->remove_noise("'<\s*style\s*>(.*?)<\s*/\s*style\s*>'is");
    834.         // strip out preformatted tags
    835.         $this->remove_noise("'<\s*(?:code)[^>]*>(.*?)<\s*/\s*(?:code)\s*>'is");
    836.         // strip out server side scripts
    837.         $this->remove_noise("'(<\?)(.*?)(\?>)'s", true);
    838.         // strip smarty scripts
    839.         $this->remove_noise("'(\{\w)(.*?)(\})'s", true);
    840.  
    841.         // parsing
    842.         while ($this->parse());
    843.         // end
    844.         $this->root->_[HDOM_INFO_END] = $this->cursor;
    845.         $this->parse_charset();
    846.     }
    847.  
    848.     // load html from file
    849.     function load_file() {
    850.         $args = func_get_args();
    851.         $this->load(call_user_func_array('file_get_contents', $args), true);
    852.         // Per the simple_html_dom repositiry this is a planned upgrade to the codebase.
    853.         // Throw an error if we can't properly load the dom.
    854.         if (($error=error_get_last())!==null) {
    855.             $this->clear();
    856.             return false;
    857.         }
    858.     }
    859.  
    860.     // set callback function
    861.     function set_callback($function_name) {
    862.         $this->callback = $function_name;
    863.     }
    864.  
    865.     // remove callback function
    866.     function remove_callback() {
    867.         $this->callback = null;
    868.     }
    869.  
    870.     // save dom as string
    871.     function save($filepath='') {
    872.         $ret = $this->root->innertext();
    873.         if ($filepath!=='') file_put_contents($filepath, $ret, LOCK_EX);
    874.         return $ret;
    875.     }
    876.  
    877.     // find dom node by css selector
    878.     // Paperg - allow us to specify that we want case insensitive testing of the value of the selector.
    879.     function find($selector, $idx=null, $lowercase=false) {
    880.         return $this->root->find($selector, $idx, $lowercase);
    881.     }
    882.  
    883.     // clean up memory due to php5 circular references memory leak...
    884.     function clear() {
    885.         foreach ($this->nodes as $n) {$n->clear(); $n = null;}
    886.         // This add next line is documented in the sourceforge repository. 2977248 as a fix for ongoing memory leaks that occur even with the use of clear.
    887.         if (isset($this->children)) foreach ($this->children as $n) {$n->clear(); $n = null;}
    888.         if (isset($this->parent)) {$this->parent->clear(); unset($this->parent);}
    889.         if (isset($this->root)) {$this->root->clear(); unset($this->root);}
    890.         unset($this->doc);
    891.         unset($this->noise);
    892.     }
    893.  
    894.     function dump($show_attr=true) {
    895.         $this->root->dump($show_attr);
    896.     }
    897.  
    898.     // prepare HTML data and init everything
    899.     protected function prepare($str, $lowercase=true, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT) {
    900.         $this->clear();
    901.  
    902.         // set the length of content before we do anything to it.
    903.         $this->size = strlen($str);
    904.  
    905.         //before we save the string as the doc...  strip out the \r \n's if we are told to.
    906.         if ($stripRN) {
    907.             $str = str_replace("\r", " ", $str);
    908.             $str = str_replace("\n", " ", $str);
    909.         }
    910.  
    911.         $this->doc = $str;
    912.         $this->pos = 0;
    913.         $this->cursor = 1;
    914.         $this->noise = array();
    915.         $this->nodes = array();
    916.         $this->lowercase = $lowercase;
    917.         $this->default_br_text = $defaultBRText;
    918.         $this->root = new simple_html_dom_node($this);
    919.         $this->root->tag = 'root';
    920.         $this->root->_[HDOM_INFO_BEGIN] = -1;
    921.         $this->root->nodetype = HDOM_TYPE_ROOT;
    922.         $this->parent = $this->root;
    923.         if ($this->size>0) $this->char = $this->doc[0];
    924.     }
    925.  
    926.     // parse html content
    927.     protected function parse() {
    928.         if (($s = $this->copy_until_char('<'))==='')
    929.             return $this->read_tag();
    930.  
    931.         // text
    932.         $node = new simple_html_dom_node($this);
    933.         ++$this->cursor;
    934.         $node->_[HDOM_INFO_TEXT] = $s;
    935.         $this->link_nodes($node, false);
    936.         return true;
    937.     }
    938.  
    939.     // PAPERG - dkchou - added this to try to identify the character set of the page we have just parsed so we know better how to spit it out later.
    940.     // NOTE:  IF you provide a routine called get_last_retrieve_url_contents_content_type which returns the CURLINFO_CONTENT_TYPE fromt he last curl_exec
    941.     // (or the content_type header fromt eh last transfer), we will parse THAT, and if a charset is specified, we will use it over any other mechanism.
    942.     protected function parse_charset()
    943.     {
    944.         global $debugObject;
    945.  
    946.         $charset = null;
    947.  
    948.         if (function_exists('get_last_retrieve_url_contents_content_type'))
    949.         {
    950.             $contentTypeHeader = get_last_retrieve_url_contents_content_type();
    951.             $success = preg_match('/charset=(.+)/', $contentTypeHeader, $matches);
    952.             if ($success)
    953.             {
    954.                 $charset = $matches[1];
    955.                 if (is_object($debugObject)) {$debugObject->debugLog(2, 'header content-type found charset of: ' . $charset);}
    956.             }
    957.  
    958.         }
    959.  
    960.         if (empty($charset))
    961.         {
    962.             $el = $this->root->find('meta[http-equiv=Content-Type]',0);
    963.             if (!empty($el))
    964.             {
    965.                 $fullvalue = $el->content;
    966.                 if (is_object($debugObject)) {$debugObject->debugLog(2, 'meta content-type tag found' . $fullValue);}
    967.  
    968.                 if (!empty($fullvalue))
    969.                 {
    970.                     $success = preg_match('/charset=(.+)/', $fullvalue, $matches);
    971.                     if ($success)
    972.                     {
    973.                         $charset = $matches[1];
    974.                     }
    975.                     else
    976.                     {
    977.                         // If there is a meta tag, and they don't specify the character set, research says that it's typically ISO-8859-1
    978.                         if (is_object($debugObject)) {$debugObject->debugLog(2, 'meta content-type tag couldn\'t be parsed. using iso-8859 default.');}
    979.                         $charset = 'ISO-8859-1';
    980.                     }
    981.                 }
    982.             }
    983.         }
    984.  
    985.         // If we couldn't find a charset above, then lets try to detect one based on the text we got...
    986.         if (empty($charset))
    987.         {
    988.             // Have php try to detect the encoding from the text given to us.
    989.             $charset = mb_detect_encoding($this->root->plaintext . "ascii", $encoding_list = array( "UTF-8", "CP1252" ) );
    990.             if (is_object($debugObject)) {$debugObject->debugLog(2, 'mb_detect found: ' . $charset);}
    991.  
    992.             // and if this doesn't work...  then we need to just wrongheadedly assume it's UTF-8 so that we can move on - cause this will usually give us most of what we need...
    993.             if ($charset === false)
    994.             {
    995.                 if (is_object($debugObject)) {$debugObject->debugLog(2, 'since mb_detect failed - using default of utf-8');}
    996.                 $charset = 'UTF-8';
    997.             }
    998.         }
    999.  
    1000.         // Since CP1252 is a superset, if we get one of it's subsets, we want it instead.
    1001.         if ((strtolower($charset) == strtolower('ISO-8859-1')) || (strtolower($charset) == strtolower('Latin1')) || (strtolower($charset) == strtolower('Latin-1')))
    1002.         {
    1003.             if (is_object($debugObject)) {$debugObject->debugLog(2, 'replacing ' . $charset . ' with CP1252 as its a superset');}
    1004.             $charset = 'CP1252';
    1005.         }
    1006.  
    1007.         if (is_object($debugObject)) {$debugObject->debugLog(1, 'EXIT - ' . $charset);}
    1008.  
    1009.         return $this->_charset = $charset;
    1010.     }
    1011.  
    1012.     // read tag info
    1013.     protected function read_tag() {
    1014.         if ($this->char!=='<') {
    1015.             $this->root->_[HDOM_INFO_END] = $this->cursor;
    1016.             return false;
    1017.         }
    1018.         $begin_tag_pos = $this->pos;
    1019.         $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1020.  
    1021.         // end tag
    1022.         if ($this->char==='/') {
    1023.             $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1024.             // This represetns the change in the simple_html_dom trunk from revision 180 to 181.
    1025.             // $this->skip($this->token_blank_t);
    1026.             $this->skip($this->token_blank);
    1027.             $tag = $this->copy_until_char('>');
    1028.  
    1029.             // skip attributes in end tag
    1030.             if (($pos = strpos($tag, ' '))!==false)
    1031.                 $tag = substr($tag, 0, $pos);
    1032.  
    1033.             $parent_lower = strtolower($this->parent->tag);
    1034.             $tag_lower = strtolower($tag);
    1035.  
    1036.             if ($parent_lower!==$tag_lower) {
    1037.                 if (isset($this->optional_closing_tags[$parent_lower]) && isset($this->block_tags[$tag_lower])) {
    1038.                     $this->parent->_[HDOM_INFO_END] = 0;
    1039.                     $org_parent = $this->parent;
    1040.  
    1041.                     while (($this->parent->parent) && strtolower($this->parent->tag)!==$tag_lower)
    1042.                         $this->parent = $this->parent->parent;
    1043.  
    1044.                     if (strtolower($this->parent->tag)!==$tag_lower) {
    1045.                         $this->parent = $org_parent; // restore origonal parent
    1046.                         if ($this->parent->parent) $this->parent = $this->parent->parent;
    1047.                         $this->parent->_[HDOM_INFO_END] = $this->cursor;
    1048.                         return $this->as_text_node($tag);
    1049.                     }
    1050.                 }
    1051.                 else if (($this->parent->parent) && isset($this->block_tags[$tag_lower])) {
    1052.                     $this->parent->_[HDOM_INFO_END] = 0;
    1053.                     $org_parent = $this->parent;
    1054.  
    1055.                     while (($this->parent->parent) && strtolower($this->parent->tag)!==$tag_lower)
    1056.                         $this->parent = $this->parent->parent;
    1057.  
    1058.                     if (strtolower($this->parent->tag)!==$tag_lower) {
    1059.                         $this->parent = $org_parent; // restore origonal parent
    1060.                         $this->parent->_[HDOM_INFO_END] = $this->cursor;
    1061.                         return $this->as_text_node($tag);
    1062.                     }
    1063.                 }
    1064.                 else if (($this->parent->parent) && strtolower($this->parent->parent->tag)===$tag_lower) {
    1065.                     $this->parent->_[HDOM_INFO_END] = 0;
    1066.                     $this->parent = $this->parent->parent;
    1067.                 }
    1068.                 else
    1069.                     return $this->as_text_node($tag);
    1070.             }
    1071.  
    1072.             $this->parent->_[HDOM_INFO_END] = $this->cursor;
    1073.             if ($this->parent->parent) $this->parent = $this->parent->parent;
    1074.  
    1075.             $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1076.             return true;
    1077.         }
    1078.  
    1079.         $node = new simple_html_dom_node($this);
    1080.         $node->_[HDOM_INFO_BEGIN] = $this->cursor;
    1081.         ++$this->cursor;
    1082.         $tag = $this->copy_until($this->token_slash);
    1083.         $node->tag_start = $begin_tag_pos;
    1084.  
    1085.         // doctype, cdata & comments...
    1086.         if (isset($tag[0]) && $tag[0]==='!') {
    1087.             $node->_[HDOM_INFO_TEXT] = '<' . $tag . $this->copy_until_char('>');
    1088.  
    1089.             if (isset($tag[2]) && $tag[1]==='-' && $tag[2]==='-') {
    1090.                 $node->nodetype = HDOM_TYPE_COMMENT;
    1091.                 $node->tag = 'comment';
    1092.             } else {
    1093.                 $node->nodetype = HDOM_TYPE_UNKNOWN;
    1094.                 $node->tag = 'unknown';
    1095.             }
    1096.             if ($this->char==='>') $node->_[HDOM_INFO_TEXT].='>';
    1097.             $this->link_nodes($node, true);
    1098.             $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1099.             return true;
    1100.         }
    1101.  
    1102.         // text
    1103.         if ($pos=strpos($tag, '<')!==false) {
    1104.             $tag = '<' . substr($tag, 0, -1);
    1105.             $node->_[HDOM_INFO_TEXT] = $tag;
    1106.             $this->link_nodes($node, false);
    1107.             $this->char = $this->doc[--$this->pos]; // prev
    1108.             return true;
    1109.         }
    1110.  
    1111.         if (!preg_match("/^[\w-:]+$/", $tag)) {
    1112.             $node->_[HDOM_INFO_TEXT] = '<' . $tag . $this->copy_until('<>');
    1113.             if ($this->char==='<') {
    1114.                 $this->link_nodes($node, false);
    1115.                 return true;
    1116.             }
    1117.  
    1118.             if ($this->char==='>') $node->_[HDOM_INFO_TEXT].='>';
    1119.             $this->link_nodes($node, false);
    1120.             $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1121.             return true;
    1122.         }
    1123.  
    1124.         // begin tag
    1125.         $node->nodetype = HDOM_TYPE_ELEMENT;
    1126.         $tag_lower = strtolower($tag);
    1127.         $node->tag = ($this->lowercase) ? $tag_lower : $tag;
    1128.  
    1129.         // handle optional closing tags
    1130.         if (isset($this->optional_closing_tags[$tag_lower]) ) {
    1131.             while (isset($this->optional_closing_tags[$tag_lower][strtolower($this->parent->tag)])) {
    1132.                 $this->parent->_[HDOM_INFO_END] = 0;
    1133.                 $this->parent = $this->parent->parent;
    1134.             }
    1135.             $node->parent = $this->parent;
    1136.         }
    1137.  
    1138.         $guard = 0; // prevent infinity loop
    1139.         $space = array($this->copy_skip($this->token_blank), '', '');
    1140.  
    1141.         // attributes
    1142.         do
    1143.         {
    1144.             if ($this->char!==null && $space[0]==='') break;
    1145.             $name = $this->copy_until($this->token_equal);
    1146.             if ($guard===$this->pos) {
    1147.                 $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1148.                 continue;
    1149.             }
    1150.             $guard = $this->pos;
    1151.  
    1152.             // handle endless '<'
    1153.             if ($this->pos>=$this->size-1 && $this->char!=='>') {
    1154.                 $node->nodetype = HDOM_TYPE_TEXT;
    1155.                 $node->_[HDOM_INFO_END] = 0;
    1156.                 $node->_[HDOM_INFO_TEXT] = '<'.$tag . $space[0] . $name;
    1157.                 $node->tag = 'text';
    1158.                 $this->link_nodes($node, false);
    1159.                 return true;
    1160.             }
    1161.  
    1162.             // handle mismatch '<'
    1163.             if ($this->doc[$this->pos-1]=='<') {
    1164.                 $node->nodetype = HDOM_TYPE_TEXT;
    1165.                 $node->tag = 'text';
    1166.                 $node->attr = array();
    1167.                 $node->_[HDOM_INFO_END] = 0;
    1168.                 $node->_[HDOM_INFO_TEXT] = substr($this->doc, $begin_tag_pos, $this->pos-$begin_tag_pos-1);
    1169.                 $this->pos -= 2;
    1170.                 $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1171.                 $this->link_nodes($node, false);
    1172.                 return true;
    1173.             }
    1174.  
    1175.             if ($name!=='/' && $name!=='') {
    1176.                 $space[1] = $this->copy_skip($this->token_blank);
    1177.                 $name = $this->restore_noise($name);
    1178.                 if ($this->lowercase) $name = strtolower($name);
    1179.                 if ($this->char==='=') {
    1180.                     $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1181.                     $this->parse_attr($node, $name, $space);
    1182.                 }
    1183.                 else {
    1184.                     //no value attr: nowrap, checked selected...
    1185.                     $node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_NO;
    1186.                     $node->attr[$name] = true;
    1187.                     if ($this->char!='>') $this->char = $this->doc[--$this->pos]; // prev
    1188.                 }
    1189.                 $node->_[HDOM_INFO_SPACE][] = $space;
    1190.                 $space = array($this->copy_skip($this->token_blank), '', '');
    1191.             }
    1192.             else
    1193.                 break;
    1194.         } while ($this->char!=='>' && $this->char!=='/');
    1195.  
    1196.         $this->link_nodes($node, true);
    1197.         $node->_[HDOM_INFO_ENDSPACE] = $space[0];
    1198.  
    1199.         // check self closing
    1200.         if ($this->copy_until_char_escape('>')==='/') {
    1201.             $node->_[HDOM_INFO_ENDSPACE] .= '/';
    1202.             $node->_[HDOM_INFO_END] = 0;
    1203.         }
    1204.         else {
    1205.             // reset parent
    1206.             if (!isset($this->self_closing_tags[strtolower($node->tag)])) $this->parent = $node;
    1207.         }
    1208.         $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1209.  
    1210.         // If it's a BR tag, we need to set it's text to the default text.
    1211.         // This way when we see it in plaintext, we can generate formatting that the user wants.
    1212.         if ($node->tag == "br") {
    1213.             $node->_[HDOM_INFO_INNER] = $this->default_br_text;
    1214.         }
    1215.  
    1216.         return true;
    1217.     }
    1218.  
    1219.     // parse attributes
    1220.     protected function parse_attr($node, $name, &$space) {
    1221.         // Per sourceforge: http://sourceforge.net/tracker/?func=detail&aid=3061408&group_id=218559&atid=1044037
    1222.         // If the attribute is already defined inside a tag, only pay atetntion to the first one as opposed to the last one.
    1223.         if (isset($node->attr[$name]))
    1224.         {
    1225.             return;
    1226.         }
    1227.  
    1228.         $space[2] = $this->copy_skip($this->token_blank);
    1229.         switch ($this->char) {
    1230.             case '"':
    1231.                 $node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE;
    1232.                 $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1233.                 $node->attr[$name] = $this->restore_noise($this->copy_until_char_escape('"'));
    1234.                 $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1235.                 break;
    1236.             case '\'':
    1237.                 $node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_SINGLE;
    1238.                 $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1239.                 $node->attr[$name] = $this->restore_noise($this->copy_until_char_escape('\''));
    1240.                 $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1241.                 break;
    1242.             default:
    1243.                 $node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_NO;
    1244.                 $node->attr[$name] = $this->restore_noise($this->copy_until($this->token_attr));
    1245.         }
    1246.         // PaperG: Attributes should not have \r or \n in them, that counts as html whitespace.
    1247.         $node->attr[$name] = str_replace("\r", "", $node->attr[$name]);
    1248.         $node->attr[$name] = str_replace("\n", "", $node->attr[$name]);
    1249.         // PaperG: If this is a "class" selector, lets get rid of the preceeding and trailing space since some people leave it in the multi class case.
    1250.         if ($name == "class") {
    1251.             $node->attr[$name] = trim($node->attr[$name]);
    1252.         }
    1253.     }
    1254.  
    1255.     // link node's parent
    1256.     protected function link_nodes(&$node, $is_child) {
    1257.         $node->parent = $this->parent;
    1258.         $this->parent->nodes[] = $node;
    1259.         if ($is_child)
    1260.             $this->parent->children[] = $node;
    1261.     }
    1262.  
    1263.     // as a text node
    1264.     protected function as_text_node($tag) {
    1265.         $node = new simple_html_dom_node($this);
    1266.         ++$this->cursor;
    1267.         $node->_[HDOM_INFO_TEXT] = '</' . $tag . '>';
    1268.         $this->link_nodes($node, false);
    1269.         $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1270.         return true;
    1271.     }
    1272.  
    1273.     protected function skip($chars) {
    1274.         $this->pos += strspn($this->doc, $chars, $this->pos);
    1275.         $this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1276.     }
    1277.  
    1278.     protected function copy_skip($chars) {
    1279.         $pos = $this->pos;
    1280.         $len = strspn($this->doc, $chars, $pos);
    1281.         $this->pos += $len;
    1282.         $this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1283.         if ($len===0) return '';
    1284.         return substr($this->doc, $pos, $len);
    1285.     }
    1286.  
    1287.     protected function copy_until($chars) {
    1288.         $pos = $this->pos;
    1289.         $len = strcspn($this->doc, $chars, $pos);
    1290.         $this->pos += $len;
    1291.         $this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
    1292.         return substr($this->doc, $pos, $len);
    1293.     }
    1294.  
    1295.     protected function copy_until_char($char) {
    1296.         if ($this->char===null) return '';
    1297.  
    1298.         if (($pos = strpos($this->doc, $char, $this->pos))===false) {
    1299.             $ret = substr($this->doc, $this->pos, $this->size-$this->pos);
    1300.             $this->char = null;
    1301.             $this->pos = $this->size;
    1302.             return $ret;
    1303.         }
    1304.  
    1305.         if ($pos===$this->pos) return '';
    1306.         $pos_old = $this->pos;
    1307.         $this->char = $this->doc[$pos];
    1308.         $this->pos = $pos;
    1309.         return substr($this->doc, $pos_old, $pos-$pos_old);
    1310.     }
    1311.  
    1312.     protected function copy_until_char_escape($char) {
    1313.         if ($this->char===null) return '';
    1314.  
    1315.         $start = $this->pos;
    1316.         while (1) {
    1317.             if (($pos = strpos($this->doc, $char, $start))===false) {
    1318.                 $ret = substr($this->doc, $this->pos, $this->size-$this->pos);
    1319.                 $this->char = null;
    1320.                 $this->pos = $this->size;
    1321.                 return $ret;
    1322.             }
    1323.  
    1324.             if ($pos===$this->pos) return '';
    1325.  
    1326.             if ($this->doc[$pos-1]==='\\') {
    1327.                 $start = $pos+1;
    1328.                 continue;
    1329.             }
    1330.  
    1331.             $pos_old = $this->pos;
    1332.             $this->char = $this->doc[$pos];
    1333.             $this->pos = $pos;
    1334.             return substr($this->doc, $pos_old, $pos-$pos_old);
    1335.         }
    1336.     }
    1337.  
    1338.     // remove noise from html content
    1339.     protected function remove_noise($pattern, $remove_tag=false) {
    1340.         $count = preg_match_all($pattern, $this->doc, $matches, PREG_SET_ORDER|PREG_OFFSET_CAPTURE);
    1341.  
    1342.         for ($i=$count-1; $i>-1; --$i) {
    1343.             $key = '___noise___'.sprintf('% 3d', count($this->noise)+100);
    1344.             $idx = ($remove_tag) ? 0 : 1;
    1345.             $this->noise[$key] = $matches[$i][$idx][0];
    1346.             $this->doc = substr_replace($this->doc, $key, $matches[$i][$idx][1], strlen($matches[$i][$idx][0]));
    1347.         }
    1348.  
    1349.         // reset the length of content
    1350.         $this->size = strlen($this->doc);
    1351.         if ($this->size>0) $this->char = $this->doc[0];
    1352.     }
    1353.  
    1354.     // restore noise to html content
    1355.     function restore_noise($text) {
    1356.         while (($pos=strpos($text, '___noise___'))!==false) {
    1357.             $key = '___noise___'.$text[$pos+11].$text[$pos+12].$text[$pos+13];
    1358.             if (isset($this->noise[$key]))
    1359.                 $text = substr($text, 0, $pos).$this->noise[$key].substr($text, $pos+14);
    1360.         }
    1361.         return $text;
    1362.     }
    1363.  
    1364.     function __toString() {
    1365.         return $this->root->innertext();
    1366.     }
    1367.  
    1368.     function __get($name) {
    1369.         switch ($name) {
    1370.             case 'outertext':
    1371.                 return $this->root->innertext();
    1372.             case 'innertext':
    1373.                 return $this->root->innertext();
    1374.             case 'plaintext':
    1375.                 return $this->root->text();
    1376.             case 'charset':
    1377.                 return $this->_charset;
    1378.             case 'target_charset':
    1379.                 return $this->_target_charset;
    1380.         }
    1381.     }
    1382.  
    1383.     // camel naming conventions
    1384.     function childNodes($idx=-1) {return $this->root->childNodes($idx);}
    1385.     function firstChild() {return $this->root->first_child();}
    1386.     function lastChild() {return $this->root->last_child();}
    1387.     function getElementById($id) {return $this->find("#$id", 0);}
    1388.     function getElementsById($id, $idx=null) {return $this->find("#$id", $idx);}
    1389.     function getElementByTagName($name) {return $this->find($name, 0);}
    1390.     function getElementsByTagName($name, $idx=-1) {return $this->find($name, $idx);}
    1391.     function loadFile() {$args = func_get_args();$this->load_file($args);}
    1392. }
    1393.  
    1394. ?>
     
  10. metadon

    metadon Активный пользователь

    С нами с:
    6 фев 2006
    Сообщения:
    779
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Так через echo всё работает нормально? а в базу не записывает?
     
  11. sharunm

    sharunm Активный пользователь

    С нами с:
    16 ноя 2014
    Сообщения:
    58
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Да, именно, так

    Добавлено спустя 1 минуту 16 секунд:
    Re: Пишу простенький парсер. Проблема с записью результатов в БД
    Только через echo он в конце приписывает еще раз CHERY#AMULET, не знаю, почему

    Добавлено спустя 5 минут 57 секунд:
    Re: Пишу простенький парсер. Проблема с записью результатов в БД
    Проблема, по-моему, с переменными $cars, $model. Из-за них не записывается. Сейчас попробую cars и model записать в массив
     
  12. metadon

    metadon Активный пользователь

    С нами с:
    6 фев 2006
    Сообщения:
    779
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Я давал выше ссылку как делать отладку, тебе там всё понятно?
    Приписки там взялись по тому что ты сам их туда добавил
     
  13. sharunm

    sharunm Активный пользователь

    С нами с:
    16 ноя 2014
    Сообщения:
    58
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Пробовал так, но не работает. Есть идея, в чем ошибка? Взгляни во внутрь цикла. Как-то я не так записал в массив.
    Код (Text):
    1. <?php
    2. // example of how to use advanced selector features
    3. include('../config.php');
    4. include('../simple_html_dom.php');
    5. $html = file_get_html('http://relines.ru/catalog/chery-amulet/');
    6. $count_pars = count ($html->find('p.b-catalog__item__sku a'));
    7. $car='CHERY';
    8. $model="Amulet";
    9. echo 'it works <br/>'.$count_pars.'<br/>';
    10.  
    11. $element_article=$html->find('p.b-catalog__item__sku a');
    12. $element_name=$html->find('p.b-catalog__item__t a');
    13. $cars_arr =array();
    14. $models_arr=array();
    15.  
    16. for($i = 0; $i <= $count_pars; $i++)
    17.   {
    18. $cars_arr[$i]=$cars;
    19. $models_arr[$i]=$model;
    20.  
    21. echo $element_article[$i]->innertext.'#'. $element_name[$i]->innertext.'#'.$cars_arr[$i].'#'.$models_arr[$i].'<br/>';
    22.  
    23. //mysql_query("
    24.  //   INSERT INTO `parts_temp` (`tb_parts_name`, `tb_parts_code`)
    25.   //      VALUES ('{$element_name[$i]->innertext}', '{$element_article[$i]->innertext}')");
    26.  // }
    27.  
    28. ?>
    Добавлено спустя 3 минуты 1 секунду:
    Re: Пишу простенький парсер. Проблема с записью результатов в БД
    Я пробовал смотреть, поэтому многое поправил, доосмыслил. Но я второй день изучаю php. Указанный выше пример работает, если не добавлять переменные названия марки и модели. Все записывает четко в БД.
     
  14. smitt

    smitt Старожил

    С нами с:
    3 янв 2012
    Сообщения:
    3.166
    Симпатии:
    65
    Re: Пишу простенький парсер. Проблема с записью результатов

    ini_set('display_errors', '1');
    error_reporting(E_ALL);

    и смотри на что ругается
     
  15. metadon

    metadon Активный пользователь

    С нами с:
    6 фев 2006
    Сообщения:
    779
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Ну если php второй день изучаешь, то начни с основ, а ещё лучше понятие алгоритма поучи.
    Тебе нужно каждую переменную посмотреть, что в ней находиться, и понять всё ли на своих местах
     
  16. sharunm

    sharunm Активный пользователь

    С нами с:
    16 ноя 2014
    Сообщения:
    58
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Вот я и решаю практическую задачку. Я не могу понять, почему марка и модель не записываются. Просмотрю все.
     
  17. metadon

    metadon Активный пользователь

    С нами с:
    6 фев 2006
    Сообщения:
    779
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Посмотри ещё какой sql запрос формируется и его в phpmyadmin протестируй
     
  18. sharunm

    sharunm Активный пользователь

    С нами с:
    16 ноя 2014
    Сообщения:
    58
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Просто, подскажите, как записывать в таких случаях значение некоторой переменной ($car) в БД 60 раз с каждой деталью с помощью цикла. Ниже два примера. Один работает, другой не работает:
    Этот не записывает в БД:
    Код (Text):
    1.  
    2. <?php
    3.  
    4. // example of how to use advanced selector features
    5. include('../config.php');
    6. include('../simple_html_dom.php');
    7. $page_where_parse='http://relines.ru/catalog/chery-amulet/';
    8. $html = file_get_html($page_where_parse);
    9. $count_pars = count ($html->find('p.b-catalog__item__sku a'));
    10. $car='CHERY';
    11. $model="Amulet";
    12. //проверяю скрипт на ошибки. Если выводится это, то ошибок в синтаксисе нет, по идее.
    13. echo 'it works <br/>'.$count_pars.'<br/>';
    14.  
    15. $element_article=$html->find('p.b-catalog__item__sku a');
    16. $element_name=$html->find('p.b-catalog__item__t a');
    17. $cars_arr =array();
    18. $models_arr=array();
    19.  
    20. for($i = 0; $i <= $count_pars; $i++)
    21.   {
    22. //не знаю, зачем объявил эти переменные глобальными, через echo выводит значения элементов и без этого
    23. global $car, $model;
    24. $cars_arr[$i]=$car;
    25. $models_arr[$i]=$model;
    26.  
    27. //запись в бд.
    28. mysql_query("
    29. INSERT INTO `parts_temp` (`tb_parts_name`, `tb_parts_code`, 'tb_cars_manufacture')
    30. VALUES ('{$element_name[$i]->innertext}', '{$element_article[$i]->innertext}', '{$cars_arr[$i]}')");
    31.   }
    32.  
    33. //просто проверяю, записалось ли в массив, вывожу значение последнего элемента
    34. echo $cars_arr[$count_pars].'<br/>';
    35. echo $models_arr[$count_pars].'<br/>';
    36. ?>
    А этот записывает в БД:.
    Разница между примерами в том, что в нижнем нет записи в столбец tb_cars_manufacture значениев элемента массива, которые я изобразил так '{$cars_arr[$i]}'. Я, вроде понимаю, что проблема именно в этом и есть. Поэтому спрашиваю совета, как записать значение переменной $car в столбец tb_cars_manufacture с каждой записью. Можете объяснить, почему это '{$element_article[$i]->innertext}' записывается, а это '{$cars_arr[$i]}' не записывается само и остальные записи тоже не позволяет записать. Спасибо.
    Работающий вариант:
    Код (Text):
    1.  
    2. <?php
    3.  
    4. // example of how to use advanced selector features
    5. include('../config.php');
    6. include('../simple_html_dom.php');
    7. $page_where_parse='http://relines.ru/catalog/chery-amulet/';
    8. $html = file_get_html($page_where_parse);
    9. $count_pars = count ($html->find('p.b-catalog__item__sku a'));
    10. $car='CHERY';
    11. $model="Amulet";
    12. //проверяю скрипт на ошибки. Если выводится это, то ошибок в синтаксисе нет, по идее.
    13. echo 'it works <br/>'.$count_pars.'<br/>';
    14.  
    15. $element_article=$html->find('p.b-catalog__item__sku a');
    16. $element_name=$html->find('p.b-catalog__item__t a');
    17. $cars_arr =array();
    18. $models_arr=array();
    19.  
    20. for($i = 0; $i <= $count_pars; $i++)
    21.   {
    22. //не знаю, зачем объявил эти переменные глобальными, через echo выводит значения элементов и без этого
    23. global $car, $model;
    24. $cars_arr[$i]=$car;
    25. $models_arr[$i]=$model;
    26.  
    27. //запись в бд.
    28. mysql_query("
    29. INSERT INTO `parts_temp` (`tb_parts_name`, `tb_parts_code`)
    30. VALUES ('{$element_name[$i]->innertext}', '{$element_article[$i]->innertext}')");
    31.   }
    32.  
    33. //просто проверяю, записалось ли в массив, вывожу значение последнего элемента
    34. echo $cars_arr[$count_pars].'<br/>';
    35. echo $models_arr[$count_pars].'<br/>';
    36. ?>
     
  19. Ganzal

    Ganzal Суперстар
    Команда форума Модератор

    С нами с:
    15 мар 2007
    Сообщения:
    9.893
    Симпатии:
    965
    Re: Пишу простенький парсер. Проблема с записью результатов

    $cars_arr[$i] - а что лежит в этом ключе? какой тип данных?
     
  20. sharunm

    sharunm Активный пользователь

    С нами с:
    16 ноя 2014
    Сообщения:
    58
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Изначально я пробовал сразу вставить в БД значение переменной $car, но у меня не получилось, я решил создать массив $cars_arr() и каждому его элементу присвоить значение переменной $car, собственно элентов в этом массиве столько же, сколько их в $element_article, посчитанных с помощью, в данном случае, $count_pars = count ($html->find('p.b-catalog__item__sku a')). И значения массивов выводятся (вне тела цикла я поместил код echo $cars_arr[$count_pars].'<br/>'; echo $models_arr[$count_pars].'<br/>';, который выводит последние значения данных массивов).
     
  21. metadon

    metadon Активный пользователь

    С нами с:
    6 фев 2006
    Сообщения:
    779
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Так покажи sql запросы которые формирует твоя программа, вместо mysql_query напиши echo и сюда результат покажи
     
  22. sharunm

    sharunm Активный пользователь

    С нами с:
    16 ноя 2014
    Сообщения:
    58
    Симпатии:
    0
  23. metadon

    metadon Активный пользователь

    С нами с:
    6 фев 2006
    Сообщения:
    779
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    А где там sql запросы? Нам их посмотреть нужно
     
  24. sharunm

    sharunm Активный пользователь

    С нами с:
    16 ноя 2014
    Сообщения:
    58
    Симпатии:
    0
    Re: Пишу простенький парсер. Проблема с записью результатов

    Вот кодик:
    Код (Text):
    1.  
    2. <?php
    3.  
    4. // example of how to use advanced selector features
    5. include('../config.php');
    6. include('../simple_html_dom.php');
    7. $page_where_parse='http://relines.ru/catalog/chery-amulet/';
    8. $html = file_get_html($page_where_parse);
    9. $count_pars = count ($html->find('p.b-catalog__item__sku a'));
    10. $car='CHERY';
    11. $model="Amulet";
    12. //проверяю скрипт на ошибки. Если выводится это, то ошибок в синтаксисе нет, по идее.
    13. echo 'it works <br/>'.$count_pars.'<br/>';
    14.  
    15. $element_article=$html->find('p.b-catalog__item__sku a');
    16. $element_name=$html->find('p.b-catalog__item__t a');
    17. $cars_arr =array();
    18. $models_arr=array();
    19.  
    20. for($i = 0; $i < $count_pars; $i++)
    21.   {
    22. //не знаю, зачем объявил эти переменные глобальными, через echo выводит значения элементов и без этого
    23. global $car, $model;
    24. $cars_arr[$i]=$car;
    25. $models_arr[$i]=$model;
    26.  
    27. //запись в бд.
    28. //mysql_query("
    29. //INSERT INTO `parts_temp` (`tb_parts_name`, `tb_parts_code`)
    30. //VALUES ('{$element_name[$i]->innertext}', '{$element_article[$i]->innertext}')");
    31. //
    32.  
    33. echo $element_article[$i]->innertext.'      '.$element_name[$i]->innertext.'      '.$cars_arr[$i].'      '.$models_arr[$i].'<br/>';
    34.  
    35. }
    36.  
    37. //просто проверяю, записалось ли в массив, вывожу значение последнего элемента
    38. echo $cars_arr[$count_pars].'<br/>';
    39. echo $models_arr[$count_pars].'<br/>';
    40. ?>
    Добавлено спустя 10 минут 4 секунды:
    Re: Пишу простенький парсер. Проблема с записью результатов в БД
    http://pars1.svdmag.ru/mylessons/count.php Улучшил вывод для удобства

    Добавлено спустя 1 минуту 58 секунд:
    Re: Пишу простенький парсер. Проблема с записью результатов в БД
    Сейчас код выглядит так:
    Код (Text):
    1.  
    2. <?php
    3.  
    4. // example of how to use advanced selector features
    5. include('../config.php');
    6. include('../simple_html_dom.php');
    7. $page_where_parse='http://relines.ru/catalog/chery-amulet/';
    8. $html = file_get_html($page_where_parse);
    9. $count_pars = count ($html->find('p.b-catalog__item__sku a'));
    10. $car='CHERY';
    11. $model="Amulet";
    12. //проверяю скрипт на ошибки. Если выводится это, то ошибок в синтаксисе нет, по идее.
    13. echo 'it works <br/>'.$count_pars.'<br/>';
    14.  
    15. $element_article=$html->find('p.b-catalog__item__sku a');
    16. $element_name=$html->find('p.b-catalog__item__t a');
    17. $cars_arr =array();
    18. $models_arr=array();
    19.  
    20. ?>
    21. <html>
    22. <head>
    23. <title>Простенький парсер</title>
    24. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    25. </head>
    26. <body>
    27. <table border="1">
    28.  
    29. <?php
    30.  
    31. for($i = 0; $i < $count_pars; $i++)
    32.   {
    33. //не знаю, зачем объявил эти переменные глобальными, через echo выводит значения элементов и без этого
    34. global $car, $model;
    35. $cars_arr[$i]=$car;
    36. $models_arr[$i]=$model;
    37.  
    38. //запись в бд.
    39. //mysql_query("
    40. //INSERT INTO `parts_temp` (`tb_parts_name`, `tb_parts_code`)
    41. //VALUES ('{$element_name[$i]->innertext}', '{$element_article[$i]->innertext}')");
    42. //
    43.  
    44. echo '<tr><td>'.$element_article[$i]->innertext.'</td><td>'.$element_name[$i]->innertext.'</td><td>'.$cars_arr[$i].'</td><td>'.$models_arr[$i].'</td></tr>';
    45.  
    46. //запись в бд.
    47. mysql_query("
    48. INSERT INTO `parts_temp` (`tb_parts_name`, `tb_parts_code`, 'tb_cars_manufacture')
    49. VALUES ('{$element_name[$i]->innertext}', '{$element_article[$i]->innertext}', '{$cars_arr[$i]}')");
    50.  
    51. }
    52.  
    53. //просто проверяю, записалось ли в массив, вывожу значение последнего элемента
    54. echo $cars_arr[$count_pars].'<br/>';
    55. echo $models_arr[$count_pars].'<br/>';
    56. ?>
    57. </table>
    58. </body>
    59. </html>
     
  25. metadon

    metadon Активный пользователь

    С нами с:
    6 фев 2006
    Сообщения:
    779
    Симпатии:
    0
    Это
    Код (PHP):
    1. mysql_query("INSERT INTO `parts_temp` (`tb_parts_name`, `tb_parts_code`, 'tb_cars_manufacture')
    2. VALUES ('{$element_name[$i]->innertext}', '{$element_article[$i]->innertext}', '{$cars_arr[$i]}')");
    3.  
    замени на это:
    Код (PHP):
    1. echo "INSERT INTO `parts_temp` (`tb_parts_name`, `tb_parts_code`, 'tb_cars_manufacture')
    2. VALUES ('{$element_name[$i]->innertext}', '{$element_article[$i]->innertext}', '{$cars_arr[$i]}')";
    3.