【问题标题】:PHP problem with DOM parsingDOM解析的PHP问题
【发布时间】:2010-10-11 12:13:56
【问题描述】:

下面粘贴的代码适用于我的 PC,但不适用于我的主机(安装了 PHP 5.2.13)。

$source = file_get_contents('http://example.com/example', 0);
$dom = new DOMDocument;
@$dom->loadHTML($source);
$dom->preserveWhiteSpace = false;

$xpath = new DOMXPath($dom);
$tags = $xpath->query('//div[@class="item"]');

$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n<root>\r\n";

foreach($tags as $tag)
    $xml .= "\t<tag>" . trim($tag->nodeValue) . "</tag>\r\n";

$xml .= '</root>';

$xml_file = 'tags.xml';
$fopen_handle = fopen($xml_file, 'w+');
fwrite($fopen_handle, $xml);
fclose($fopen_handle);

在我的主机上,foreach 循环不执行,即我在 XML 中只得到这个:

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

提前致谢。

【问题讨论】:

  • 这需要基本的调试。 error_reporting(E_ALL); 的结果是什么?

标签: php http foreach domxpath


【解决方案1】:

您的主机不支持 file_get_contents(allow_url_fopen 是设置 iirc)

试试这个:

$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, 'http://example.com');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    相关资源
    最近更新 更多