【问题标题】:PHP ganon dom parser get next element when match is foundPHP ganon dom解析器在找到匹配时获取下一个元素
【发布时间】:2013-04-21 20:16:23
【问题描述】:

我正在从 ganon dom 解析器解析和 html dom 字符串,并希望在前一个元素上找到匹配项时获取下一个元素纯文本,例如我的 html 就像

<tr class="last even">
   <th class="label">SKU</th>
   <td class="data last">some sku here i want to get </td> 
</tr>

我暂时使用了以下代码

$html = str_get_dom('html string here');
foreach ($html('th.label') as $elem){
                if($elem->getPlainText()=='SKU'){ //this is right
                    echo $elem->getSibling(1)->getPlainText(); // this is not working
                }
            }

如果找到带有类标签和innerhtml SKU的th,则从下一个兄弟中获取innerhtml,即SKU值

请帮忙解决这个问题。

【问题讨论】:

  • $html()?变量函数?执行我,我去抓我的眼睛。
  • 是的,我知道。我的评论仍然成立。变量函数是邪恶的,就像变量变量一样。
  • @MarcB 对这个问题有任何想法。

标签: php dom html-parsing ganon


【解决方案1】:

这可能是 html 的“ganon”中的错误 - 如果您以 html 为例:

$html = '<table>
                <tr class="last even">
                   <th class="label">SKU</th>
                   <td class="data last">some sku here i want to get </td> 
                </tr>
            </table>';

   $html = str_get_dom($html); 

由于某种原因,由于 html 中的新行“ganon”认为下一个元素是文本元素,然后才有欲望 td - 所以你必须这样做:

   foreach ($html('th.label') as $elem){
        if($elem->getPlainText()=='SKU'){ 
            //elem -> text node -> td node
            echo($elem->getSibling(1)->getSibling(1)->getPlainText()); 
        }
    }

如果你像这样组织你的html(没有换行):

$html = '<table>
                <tr class="last even">
                   <th class="label">SKU</th><td class="data last">some sku here i want to get </td> 
                </tr>
            </table>';

那么你的原始代码就可以工作了$elem-&gt;getSibling(1)-&gt;getPlainText()

也许可以考虑使用php simple html dom 类 - 它更直观,使用完整的 oop 方法,jquery dom 解析器喜欢并且不使用这种糟糕的 var-function 方法:):

require('simple_html_dom.php');

    $html = '<table>
                <tr class="last even">
                   <th class="label">SKU</th>
                   <td class="data last">some sku here i want to get </td> 
                </tr>
            </table>';

   $dom = str_get_html($html); 


   foreach($dom->find('th.label') as $el){
       if($el->plaintext == 'SKU'){  
            echo($el->next_sibling()->plaintext);
       }
   }

【讨论】:

  • 以前我使用过简单的 html dom 解析器,但我无法加载我的整页 html dom 并且发送超时.. 很慢很累。
  • 非常感谢 $elem->getSibling(1)->getSibling(1)->getPlainText() 它成功了。
  • 关于使用 ganon 获取 javascript 内容的任何想法我都有我的 js,例如 谢谢
  • 将脚本标签作为 dom 并获取它的内部文本 - 在简单的 dom 中就像这样,例如:$dom-&gt;find('script',0)-&gt;innertext
猜你喜欢
  • 2014-05-03
  • 2020-09-20
  • 2020-10-24
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多