如何解析外部网页的内容

时间:2014-01-23 15:16:00

标签: javascript php html

我需要知道一种创建curl脚本的方法,该脚本可以执行以下操作:

  • 登录使用POST公式的特定网页
  • 登录后我需要打开并解析一个特定的URL
  • 在此页面上我只需要具有特定已知ID的div的值。

使用PHP curl脚本可以实现这样吗?有人能给我一个解决这个问题的起点吗?

1 个答案:

答案 0 :(得分:1)

这里有一些代码可以帮助您入门。我添加了一些注释,让您了解它在每一步中的作用:

<?php

// Define the URL and the data you want to send
$url = 'http://stackoverflow.com/';
$myvars = 'myvar1=sometestdata';

// Now try and download the webpage
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );

// Create a DOMDocument for parsing the HTML
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($response);

// Find the element with an ID of 'nav-questions'
$data = $dom->getElementById("nav-questions");
echo $data->nodeValue;
相关问题