2016-01-22 22 views
1

IM现在正在做的是我有一个文本区域供用户复制和粘贴HTML代码。 我想获得该HTML文件的某个元素。 在纯HTML中,这可以通过jQuery选择器 来完成,但我认为它是一个完全不同的事情时,HTML代码是在变量上,并认为是一个字符串。 我怎样才能得到某种元素的位置?使用选择器搜索PHP变量或方式的HTML代码(字符串)

代码:

 function searchHtml() { 
      $html = $_POST; // text area input contains html code 
      $selector = "#rso > div > div > div:nth-child(1) > div > h3 > a"; //example - the a element with hello world 
      $getValue = getValueBySelector($selector); //will return hello world  
     } 
     function getValueBySelector($selector) { 
      //what will i do here? 
     } 
     searchHtml(); 

回答

1

你可以看一下SimpleHTMLDom解析器(在http://simplehtmldom.sourceforge.net/manual.htm手册)。这是解析HTML代码来查找和提取各种元素及其属性的强大工具。

为您的特定情况下,你可以使用

// Create a DOM object from the input string 
$htmlDom = str_get_html($html); 
// Find the required element 
$e = $htmlDom->find($selector); 

哦,您对所提供的输入值传递给getValueBySelector()函数:-)

+0

我......从来没有。想到..有那样的东西..在那里。我相当震惊。我认为这将解决我的问题!不好先给它一个测试。一旦验证,病人将其标记为正确的答案。 :) 万分感谢! –

+0

很高兴帮助@JosephBada,让知情的情况下,你需要进一步的帮助! –

+0

这就是我需要的。非常感谢! –