2009-11-20 144 views
0

我有一個XML飼料這個XML飼料現在我試着解析的內容,特別是在<REDIRECT></REDIRECT>標籤的內容。 我使用下面的代碼來嘗試和解析內容,但它不工作,我不知道我做錯了什麼。在此<a href="http://www.supashare.net/test.xml" rel="nofollow noreferrer">url</a></p> <p>解析使用PHP

$xml_file = $ADurl; 

$xml_headline_key = "*XML*RESULTS*LISTING*REDIRECT"; 
$xml_description_key = "*XML*RESULTS*LISTING*REDIRECT"; 

$story_array = array(); 

$counter = 0; 
class xml_story{ 
    var $headline, $description; 
} 

function startTag($parser, $data){ 
    global $current_tag; 
    $current_tag .= "*$data"; 
} 

function endTag($parser, $data){ 
    global $current_tag; 
    $tag_key = strrpos($current_tag, '*'); 
    $current_tag = substr($current_tag, 0, $tag_key); 
} 

function contents($parser, $data){ 
    global $current_tag, $xml_headline_key, $xml_description_key, $counter, $story_array; 
    switch($current_tag){ 
     case $xml_headline_key: 
      $story_array[$counter] = new xml_story(); 
      $story_array[$counter]->headline = $data; 
      break; 
     case $xml_description_key: 
      $story_array[$counter]->description = $data; 
      $counter++; 
      break; 
    } 
} 

$xml_parser = xml_parser_create(); 

xml_set_element_handler($xml_parser, "startTag", "endTag"); 

xml_set_character_data_handler($xml_parser, "contents"); 

$fp = fopen($xml_file, "r") or die("Could not open file"); 

$data = fread($fp, 1024) or die("Could not read file"); 

if(!(xml_parse($xml_parser, $data, feof($fp)))){ 
    die("Error on line " . xml_get_current_line_number($xml_parser)); 
} 

xml_parser_free($xml_parser); 

fclose($fp); 

回答

3

是不是有理由不能使用simplexml

$xml = simplexml_load_file('http://www.supashare.net/test.xml'); 
$result = $xml->xpath('/XML/RESULTS/LISTING/REDIRECT'); 
echo $result[0]; 
+0

而與此相同,它不與遠程XML文件 – Imran 2009-11-20 19:26:59

+0

打開錯誤看看會發生什麼工作。您的服務器可能沒有啓用allow_url_fopen,在這種情況下,您將不得不編輯您的php.ini(如果可能)以啓用它。 – Galen 2009-11-20 19:49:50

+0

if simplexml_load_file will not work then replace it with this .... $ xml = simplexml_load_string(file_get_contents($ url)); 其中$ url是你想要的網址 – ChronoFish 2009-11-20 19:50:01

2
$xml = stream_get_contents($fp); 
$xml = new SimpleXMLElement($xml); 
echo $xml->RESULTS->LISTING->REDIRECT; 
+0

那麼問題是,它無法解析遠程XML文件。 – Imran 2009-11-20 19:26:19

+0

你是什麼意思?你的服務器本地有XML文件嗎?如果是這樣,請將URL更改爲該文件名,它將起作用。 – 2009-11-20 19:28:30

+0

不,xml文件位於另一臺服務器上的另一臺服務器上。 – Imran 2009-11-20 19:29:20

1
$doc = new DomDocument(); 
$doc->load('http://www.supashare.net/test.xml'); 
$q = new DomXPath($doc); 
echo $q->query('//REDIRECT')->item(0)->nodeValue; 
+0

我記得你從站點,你是一個我喜歡閱讀的職位的人。你能告訴我爲什麼你選擇domdocument而不是simplexml嗎? – Galen 2009-11-20 19:26:50

+0

嗯..我覺得你用別的東西混淆了我:S 至於你的答案..它不能與遠程XML文件一起工作 – Imran 2009-11-20 19:48:38

+0

它們使用相同的底層解析(libxml),所以它只是語法。我個人更喜歡DOM,因爲它是一個標準API。這只是一種偏好。 – troelskn 2009-11-20 20:05:37

相關問題