头文件

struct MemoryStruct {
  char *memory;
  size_t size;
};

c文件
创建回调函数

static size_t
WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
  size_t realsize = size * nmemb;
  struct MemoryStruct *mem = (struct MemoryStruct *)userp;

  mem->memory = erealloc(mem->memory, mem->size + realsize + 1);
  if (mem->memory == NULL) {
    /* out of memory! */
    printf("not enough memory (realloc returned NULL)n");
    exit(EXIT_FAILURE);
  }

  memcpy(&(mem->memory[mem->size]), contents, realsize);
  mem->size += realsize;
  mem->memory[mem->size] = 0;

  return realsize;
}

创建PHP函数

PHP_FUNCTION(echo_lovefang)
{
	CURL *curl;
	CURLcode res;
	struct MemoryStruct chunk;
	chunk.memory = emalloc(1);  /* will be grown as needed by the realloc above */
	chunk.size = 0;    /* no data at this point */
	//FILE *fp = fopen("/tmp/data.txt", "rb");
	curl = curl_easy_init();
	 if(curl) {
		curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
		/* example.com is redirected, so we tell libcurl to follow redirection */
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
		//curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
		/* send all data to this function  */
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
		/* Perform the request, res will get the return code */
		res = curl_easy_perform(curl);
		/* Check for errors */
		if(res != CURLE_OK)
			php_printf("curl_easy_perform() failed: %sn", curl_easy_strerror(res));
		/* always cleanup */
		curl_easy_cleanup(curl);
	  }

	   /* we're done with libcurl, so clean it up */
	 curl_global_cleanup();


	php_printf("%lu bytes retrievedn", (long)chunk.size);
	php_printf("content: %s", chunk.memory);
	if(chunk.memory)
	     efree(chunk.memory);
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注