2012-03-24 62 views
0

簡單的問題,我應該考慮。不幸的是,我無法弄清楚如何讓它工作。XML API到PHP!新開發人員,不知道如何做到這一點

我有一個看起來像這樣的XML數據表:

<leads> 
    <leadDetails> 
     <lead_id>3886961</lead_id> 
     <campaign_id>1173</campaign_id> 
     <campaign_name>Tesco vs Argos - Submit (UK)</campaign_name> 
     <subID>N/A</subID> 
     <gateway>yes</gateway> 
     <ip>109.155.249.140</ip> 
     <referring_url>http://adworkmedia.com/gTemplate.php?GID=1514&pubID=2312&sid=&ST= 
     </referring_url> 
     <date>2012-03-24 07:19:07</date> 
     <payout>$0.70</payout> 
     <status>Credited</status> 
    </leadDetails> 
</leads> 

我要補充一點,這個XML紙張未託管在我的服務器,但動態更新,因爲我得到一個新的領先優勢,通過我的網絡。如有需要,請隨時問我更多問題。

我的問題是:如何編寫一個讀取XML頁面的代碼,並將每個日期,IP和campaign_name上傳到mySQL表。

謝謝!

回答

1

嗨。

  if($xml = simplexml_load_file("the_url_of_xml")) 
      { 
       foreach($xml->leads->leadDetails as $detail) 
       { 
       $camp_id = $detail->campaign_id; 
       $camp_name = $detail->campaign_name; 
       $sql = "INSERT INTO myTable (id,name) VALUES ('$camp_id','$camp_name')";//AND so on 
       mysql_query($sql); 
      } 

      } 
1

只是一個起點,供大家參考,使用SimpleXML和PDO:

$xml = simplexml_load_file('http://yourhost.com/somefile.xml'); 
$pdo = new PDO('mysql:dbname=test;host=localhost', 'user', 'pass'); 
foreach ($xml->leadDetails as $lead) { 
    $stmt = $pdo->prepare('INSERT INTO table (createdAt, ip, campaign_name) VALUES (NOW(), ?, ?)'); 
    $stmt->execute(array(
     $_SERVER['REMOTE_ADDR'], 
     $lead->campaign_name 
    )); 
} 
1

在我看來JSON會是一種更好的格式,但對於XML來說,它非常簡單。

<?php 
$con = mysql_connect("username","password","host"); 
mysql_select_db("database_name",$con); 

$xmlObj = new SimpleXMLElement($xml); //replace $xml with your XML string. 
foreach($xmlObj->leadDetails as $details){ 
    $date = $details->date; 
    $ip = $details->ip; 
    $campaign_name = $details->campaign_name; 
    mysql_query("INSERT INTO `table_name` (`date`,`ip`,`campaign_name`) VALUES ('$date','$ip','$campaign_name')",$con); 
} 
?> 
相關問題