Import CSV file from Facebook marketing API

0

I have generated the statistics of my Facebook campaigns with the API Marketing and php ads sdk , I get access to my report and from the browser what I can download by entering an url like this:

  

www.facebook.com/ads/ads_insights/export_report?report_run_id=REPORT_ID&format=csv&access_token=TOKEN

$fileName = "campaign_insights.csv";
$graph_url = 'https://www.facebook.com/ads/ads_insights/export_report?report_run_id='.$report_run.'&format=csv&access_token='.$access_token;

$path = "campaign_insights.csv";

set_time_limit(0);
$fp = fopen ($path, 'w+');
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_URL, $graph_url);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$result = curl_exec( $ch );
var_dump($result); //siempre responde false
curl_close($ch);
fclose($fp);

My problem is when I try to save that generated file (csv) directly on my server, I tried to do it with cURL , file_get_contents but I have not succeeded, the cURL answers me empty and file_get_contents Facebook does not allow it, any idea of how I could do to save this file on my server?

Thanks.

UPDATE:

The solution is below.

    
asked by Jose Flores 15.05.2017 в 19:26
source

1 answer

0

I have already managed to find the solution, I leave it here in case it is useful to another person:

After some tests I realized that the curl answered that my browser is outdated.

Update it with:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
));

the complete code would look like this:

$fp = fopen ($path, 'w+');
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_URL, $graph_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
));
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
fclose($fp);

By doing this the problem was completely solved.

With the help of Chin Leung from Stackoverflow in English.

    
answered by 16.05.2017 / 00:49
source