0

这就是我想要做的:从 URL 下载 xml VAST 并在 PHP 中本地保存在 XML 文件中。为此,我使用了 file_get_contents 和 file_put_contents。这是我正在使用的脚本:

<?php
$tid=time();

$xml1 = file_get_contents('http://ad.afy11.net/ad?enc=4&asId=1000009566807&sf=0&ct=256');
file_put_contents("downloads/file1_$tid.xml", $xml1);
echo "<p>file 1 recorded</p>";
?>

有问题的 URL 是一个真实的 URL,它将提供一个 xml VAST 代码。我的问题是,当我保存 de 文件时,它会写入一个空的 VAST 标记:

<?xml version="1.0" encoding="UTF-8"?> <VAST version="2.0"> </VAST>

但如果我在 Firefox 上运行,它实际上会提供一些代码:

<VAST version="2.0"><Ad id="Adify"><Wrapper><AdSystem>Eyeblaster</AdSystem><VASTAdTagURI>http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=is&c=23&pl=VAST&pli=6583370&PluID=0&pos=7070&ord=4288438534]&cim=1</VASTAdTagURI><Impression>http://ad.afy11.net/ad?ipc=NMUsqYdyBUCjh4-i2HwWfK1oILM2AAAAN6-rBkSy8JNMZcuzAlj1XlSySpo6Hi7xEYULS+UgOVN5D3UuhFUVSWbFHoLE-+3su0-QnGgZgMJyiTm-R6O+yQ==</Impression><Creatives/></Wrapper></Ad></VAST>

不是 100% 的时间,他们确实限制了请求的数量,但是当我尝试使用 PHP 脚本保存文件时,这种情况更常见。

这是让 PHP 脚本模仿浏览器的一种方法吗????我不知道这是否是正确的问题,但这是我唯一能想到的为什么我在使用 php 脚本时得到一个空的 VAST 标记,而在使用浏览器时得到一个完整的标记。

有任何想法吗???

谢谢 :)

更新:在做了一些额外的研究之后,我发现了一些关于 stream_context_create 函数的信息,但我无法复制浏览器的结果。

这是我的新代码:

<?php

$tid=time();

$opts = array('http' =>
    array(
        'method'  => 'GET',
        //'user_agent '  => "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2) Gecko/20100301 Ubuntu/9.10 (karmic) Firefox/3.6",
        'header' => array(
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*\/*;q=0.8
'
        ), 
    )
);
$context  = stream_context_create($opts);


$xml1 = file_get_contents('http://ad.afy11.net/ad?enc=4&asId=1000009566807&sf=0&ct=256');
file_put_contents("downloads/file1_$tid.xml", $xml1);
echo "<p>file 1 recorded</p>";
echo "<textarea rows='6' cols='80'> $xml1 </textarea> ";
echo "<br><iframe src='http://ad.afy11.net/ad?enc=4&asId=1000009566807&sf=0&ct=256' width='960' height='300'></iframe>";
?>

我还添加了一个 iframe 来比较浏览器何时获取正确的文件以及何时没有获取 php 函数。

4

1 回答 1

4

After some research I found a solution for my problem, and I would like to share here for future reference. The idea as to pass some HTTP header with the file_get_contents. I accomplish that with this:

$opts = array(
            'http'=>array(
                        'method'=>"GET",
                        'header'=>array("Accept-language: en", "Content-Type: multipart/form-data\r\n"),
                        'user_agent'=>    $_SERVER['HTTP_USER_AGENT']
                        )
            );

$context = stream_context_create($opts); 

$xml4 = file_get_contents($url1, true, $context);

That's it, now I can get the same xml as if I was using the browser.

于 2013-05-08T13:23:03.767 回答