別のドメイン名から XML ファイルを文字列として読み込もうとしています。必要なのは、xml ファイルの < title >< /title > タグ内のテキストの配列だけなので、php4 を使用しているので、最も簡単な方法は正規表現を実行してそれらを取得することだと考えています。XMLを文字列としてロードする方法を誰かが説明できますか? ありがとう!
4 に答える
以下の例のように cURL を使用できます。正規表現ベースの 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));
}
最初に file_get_contents(' http://www.example.com/ ');を使用します。
ファイルを取得するには、var に挿入します。xml を解析した後、リンクは http://php.net/manual/en/function.xml-parse.php で、コメントに例があります
整形式の xml をロードしている場合は、文字ベースの解析をスキップして、DOM 関数を使用します。
$d = new DOMDocument;
$d->load("http://url/file.xml");
$titles = $d->getElementsByTagName('title');
if ($titles) {
echo $titles->item(0)->nodeValue;
}
PHP の設定方法が原因で DOMDocument::load() を使用できない場合は、curl を使用してファイルを取得してから、次のようにします。
$d = new DOMDocument;
$d->loadXML($grabbedfile);
...
私はスニペットとしてこの機能を持っています:
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);
$matches[1] には必要な情報が含まれています。