2009-06-01 39 views
2

我试图从一个不同的域名作为字符串加载一个XML文件。我想要的是一个< title> </title>标签的文本数组,因此我在考虑,因为我使用的是php4,最简单的方法是对它进行正则表达式来获取它们。有人可以解释如何将XML作为字符串加载吗?谢谢!PHP的:如何加载文件从不同的服务器作为字符串?

回答

2

你可以使用卷曲如下面的例子例子。我应该补充一点,基于正则表达式的XML解析通常不是一个好主意,而且使用真正的解析器可能会更好,特别是如果它更复杂。

您可能还需要添加一些正则表达式修饰符以使其跨越多行等工作,但我认为问题更多地是将内容提取到字符串中。

<?php 

$curl = curl_init('http://www.example.com'); 

//make content be returned by curl_exec rather than being printed immediately         
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 

$result = curl_exec($curl); 

if ($result !== false) { 
    if (preg_match('|<title>(.*)</title>|i', $result, $matches)) { 
     echo "Title is '{$matches[1]}'"; 
    } else { 
     //did not find the title  
    } 
} else { 
    //request failed 
    die (curl_error($curl)); 
} 
2

首次使用 file_get_contents('http://www.example.com/');

获取文件, 插入到var。 解析XML 在链路 http://php.net/manual/en/function.xml-parse.php 在评论

+0

谢谢你,我得到这个错误:“警告:file_get_contents()函数:URL文件访问服务器配置中禁用”有没有办法用cURL来做到这一点我知道已启用。谢谢! – 2009-06-01 14:27:24

1

我有这个功能的一个片段:

function getHTML($url) { 
    if($url == false || empty($url)) return false; 
    $options = array(
     CURLOPT_URL   => $url,  // URL of the page 
     CURLOPT_RETURNTRANSFER => true,  // return web page 
     CURLOPT_HEADER   => false, // don't return headers 
     CURLOPT_FOLLOWLOCATION => true,  // follow redirects 
     CURLOPT_ENCODING  => "",  // handle all encodings 
     CURLOPT_USERAGENT  => "spider", // who am i 
     CURLOPT_AUTOREFERER => true,  // set referer on redirect 
     CURLOPT_CONNECTTIMEOUT => 120,  // timeout on connect 
     CURLOPT_TIMEOUT  => 120,  // timeout on response 
     CURLOPT_MAXREDIRS  => 3,  // stop after 3 redirects 
    ); 

    $ch  = curl_init($url); 
    curl_setopt_array($ch, $options); 
    $content = curl_exec($ch); 
    $header = curl_getinfo($ch); 
    curl_close($ch); 

    //Ending all that cURL mess... 


    //Removing linebreaks,multiple whitespace and tabs for easier Regexing 
    $content = str_replace(array("\n", "\r", "\t", "\o", "\xOB"), '', $content); 
    $content = preg_replace('/\s\s+/', ' ', $content); 
    $this->profilehtml = $content; 
    return $content; 
} 

与没有换行符,制表符,多个空格返回HTML等,只有1号线。

所以,现在你这样做的preg_match:

$html = getHTML($url) 
preg_match('|<title>(.*)</title>|iUsm',$html,$matches); 

和$匹配[1]将有你需要的信息。

2

如果你加载格式良好的XML,跳过基于字符的解析,并使用DOM功能:

$d = new DOMDocument; 
$d->load("http://url/file.xml"); 
$titles = $d->getElementsByTagName('title'); 
if ($titles) { 
    echo $titles->item(0)->nodeValue; 
} 

如果您不能使用的DOMDocument :: load()方法,由于PHP是如何设置完毕后,用卷曲来获取文件,然后执行:

$d = new DOMDocument; 
$d->loadXML($grabbedfile); 
... 
相关问题