PHP DOM,仅返回部分文档 [英] PHP DOM and returning only part of document

查看:57
本文介绍了PHP DOM,仅返回部分文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现domdocument,并且以前使用过正则表达式。

I Just discovered domdocument and had previously been using regex..

我需要返回带有所有输入的整个form元素。

I need to return the entire form element with all the inputs.

我不需要创建整个文档,而只需要我可以操纵的字符串即可。我一直在弄乱下面的代码,试图使其变得有用,但到目前为止,什么都没有。

I don't need to create an entire document i just want that part, in a string that I can manipulate. I have been messing with the following chunk of code trying to make it do something useful, but so far, nothing.

在我回到正则表达式之前,有人可以理解吗?

Can anyone make sense of this before I go back to regex?

//get HTML into variable
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://www.openroadlending.com/Apply.aspx?aid=134');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$html=curl_exec($curl);

$dom = new domDocument;
@$dom->loadHTML($html);
$dom->preserveWhiteSpace=false;

$xpath = new DOMXPath($dom);
$body = $xpath->query('html/');

echo var_dump($body);

//echo $body->item(0);
$inputs = $xpath->getElementsByTagName('form');

// foreach($inputs as $in){
// $input = $in->saveHTML;
// //echo $input;
// }


推荐答案

您可以使用此函数

function DOMinnerHTML($element) 
{ 
   $innerHTML = ""; 
   $children = $element->childNodes; 
   foreach ($children as $child) 
   { 
      $tmp_dom = new DOMDocument(); 
      $tmp_dom->appendChild($tmp_dom->importNode($child, true)); 
      $innerHTML.=trim($tmp_dom->saveHTML()); 
   } 
   return $innerHTML; 
}

并像这样使用

$productspec=$dom->getElementsByTagName('form')
foreach($productspec as $data)
{ 
   echo DOMinnerHTML($data);
}

您可以使用此功能按类获取元素

and You Can Use This function for Get Element By Class

function GetBYClass($Doc,$ClassName){
    $finder = new DomXPath($Doc);
    return($finder->query("//*[contains(@class, '$ClassName')]"));
} 

此功能与此问题无关但有用

and This function Is Not Related To This Question But It Useful

function ExtractText($node) {
     if($node==NULL)return false;    
     if (XML_TEXT_NODE === $node->nodeType || XML_CDATA_SECTION_NODE === $node->nodeType) {
         return $node->nodeValue;
     } else if (XML_ELEMENT_NODE === $node->nodeType || XML_DOCUMENT_NODE === $node->nodeType || XML_DOCUMENT_FRAG_NODE === $node->nodeType) {
       if ('script' === $node->nodeName) return '';

     $text = '';
     foreach($node->childNodes as $childNode) {
        $text .= $this->extractText($childNode);
     }
     return $text;
     }
}

这篇关于PHP DOM,仅返回部分文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆