从HTML标记中提取数据

问题描述 投票:0回答:3

我有以下代码并尝试从html页面中提取属性内容的值,但它没有给出我期望的任何结果,而是仅给出空白页面。

可能是问题的任何帮助?

$url= "https://fr-ca.wordpress.org";
$html = file_get_contents($url);
  # Create a DOM parser object
   $dom = new DOMDocument();
   $dom->loadHTML($html);
   foreach ($dom->getElementsByTagName('meta') as $key ) {
   echo "<pre>";
   $tab[] = $key->getAttribute('content');
   }
   $reg= '<meta name="generator" content="(.*?)"/>';
   if (preg_match_all($reg, $html, $ar)) {
    print_r($ar);
   } 

页面来源有:

<meta name="generator" content="WP 4.5"/>
php html extract
3个回答
1
投票

试试这个:

$html = '<meta name="generator" content="WP 4.5"/>';
preg_match_all('/content="(.*)"/i', $html, $matches);
if (isset($matches[1])) {
    print_r($matches[1]);
}

1
投票

这是一个正则表达式,它将查找元标记并获取内容属性内容。它有一些外卡可以解释其他变量,如不同的名称或额外的空格等。

$html = '<meta name="generator" content="WP 4.5"/>';

preg_match_all( '#<meta.*?content=[\'"](.*?)[\'"]\s*/>#i', $tab, $results );
print_r( $results[1] ); // contains array of captures.
if( $results[1] ) {
    // code here...
}

0
投票

请这样使用......

$html = file_get_contents( $url);

    libxml_use_internal_errors( true);
    $doc = new DOMDocument;
    $doc->loadHTML( $html);
    $xpath = new DOMXpath( $doc);

    // A name attribute on a <div>???
    $nodes = $xpath->query( '//div[@name="changeable_text"]')->item( 0);

    echo $nodes->Content; 

要么

//使用卷曲...

function getHTML($url,$timeout)
{
       $ch = curl_init($url); // initialize curl with given url
       curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // set  useragent
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // write the response to a variable
       curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects if any
       curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // max. seconds to execute
       curl_setopt($ch, CURLOPT_FAILONERROR, 1); // stop when it encounters an error
       return @curl_exec($ch);
}
$html=getHTML("http://www.website.com",10);
// Find all images on webpage
foreach($html->find("img") as $element)
echo $element->src . '<br>';

// Find all links on webpage
foreach($html->find("a") as $element)
echo $element->href . '<br>';
© www.soinside.com 2019 - 2024. All rights reserved.