以某种方式存储API数据数组

时间:2013-04-02 18:54:13

标签: php mysql xml

我已经想出了如何将我的数据数组插入到mysql表中。 (谢谢你亨斯曼)。 我想知道是否有更整洁的代码可以完成我正在做的事情。 我注意到我这样做的方式只允许我插入顶级数组结果。数组显示正确,但无法获得具有相同名称的子级别节点。任何建议?也想发布任何有类似问题的人。花了一些时间才找到你们。

<?php
function upsTrack($trackingNumber) {
$data ="<?xml version=\"1.0\"?>
    <AccessRequest xml:lang='en-US'>
            <AccessLicenseNumber>AccessNumber</AccessLicenseNumber>
            <UserId>username</UserId>
            <Password>Password</Password>
    </AccessRequest>
    <?xml version=\"1.0\"?>
    <TrackRequest>
            <Request>
                    <TransactionReference>
                            <CustomerContext>
                                    <InternalKey>blah</InternalKey>
                            </CustomerContext>
                            <XpciVersion>1.0</XpciVersion>
                    </TransactionReference>
                    <RequestAction>Track</RequestAction>
            </Request>
    <TrackingNumber>$trackingNumber</TrackingNumber>    
    </TrackRequest>";
$ch = curl_init("https://www.ups.com/ups.app/xml/Track");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_TIMEOUT, 60);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
$result=curl_exec ($ch);
// echo '<!-- '. $result. ' -->';
$data = strstr($result, '<?');
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);
$params = array();
$level = array();
foreach ($vals as $xml_elem) {
if ($xml_elem['type'] == 'open') {
if (array_key_exists('attributes',$xml_elem)) {
     list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
} else {
     $level[$xml_elem['level']] = $xml_elem['tag'];
}
}
if ($xml_elem['type'] == 'complete') {
$start_level = 5;
$php_stmt = '$params';
while($start_level < $xml_elem['level']) {
     $php_stmt .= '[$level['.$start_level.']]';
     $start_level++;
}
$php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
eval($php_stmt);
}
}
curl_close($ch);
return $params;
}

if ($_POST['af0'] == 'xx1') {
if (preg_match('/^[a-z\d_]{4,80}$/i', $_POST['trackingNumber'])) {
    $cleanTrackingNumber = $_POST['trackingNumber'];
    $someArray = upsTrack("$cleanTrackingNumber");
    echo $someArray['RESPONSESTATUSDESCRIPTION'],    $someArray['SHIPPERNUMBER'],  $someArray['ADDRESSLINE1'],$someArray['CITY'],  $someArray['STATEPROVINCECODE'], $someArray['POSTALCODE'], $someArray['COUNTRYCODE'],$someArray['CODE'], $someArray['DESCRIPTION'], $someArray['VALUE'], $someArray['SHIPMENTIDENTIFICATIONNUMBER'], $someArray['PICKUPDATE'], $someArray['TRACKINGNUMBER'], $someArray['ACTIVITYLOCATION']['ADDRESS'] ['STATEPROVINCECODE'], $someArray['DATE'], $someArray['TIME'], $someArray['WEIGHT'];
} else {
    echo 'Invalid tracking number... sigh...';
}
}

?>
<?php
/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'testdb';

/*** mysql password ***/
$password = 'test123';

/*** database name ***/
$dbname = 'test';

try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';

/*** set the PDO error mode to exception ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** begin the transaction ***/
$dbh->beginTransaction();


/***  INSERT statements ***/
$dbh->exec("INSERT INTO upstrackdb ( RESPONSESTATUSDESCRIPTION, SHIPPERNUMBER,   ADDRESSLINE1, CITY, STATEPROVINCECODE, POSTALCODE, COUNTRYCODE, CODE, DESCRIPTION, VALUE, SHIPMENTIDENTIFICATIONNUMBER, PICKUPDATE, TRACKINGNUMBER, ACTIVITYLOCATION, DELIVERYDATE, DELIVERYTIME, WEIGHT) VALUES ( '$someArray[RESPONSESTATUSDESCRIPTION]',  '$someArray[SHIPPERNUMBER]', '$someArray[ADDRESSLINE1]', '$someArray[CITY]', '$someArray[STATEPROVINCECODE]', '$someArray[POSTALCODE]', '$someArray[COUNTRYCODE]', '$someArray[CODE]', '$someArray[DESCRIPTION]', '$someArray[VALUE]', '$someArray[SHIPMENTIDENTIFICATIONNUMBER]', '$someArray[PICKUPDATE]', '$someArray[TRACKINGNUMBER]', '$someArray[STATEPROVINCECODE]',  '$someArray[DATE]', '$someArray[TIME]', '$someArray[WEIGHT]')");

/*** commit the transaction ***/
$dbh->commit();

/*** echo a message to say the database was created ***/
echo 'Data entered successfully<br />';
}
catch(PDOException $e)
{
/*** roll back the transaction if we fail ***/
$dbh->rollback();

/*** echo the sql statement and error message ***/
echo $sql . '<br />' . $e->getMessage();
}
?>

以下是我得到的结果。

<!-- HTTP/1.1 200 OK
Date: Tue, 02 Apr 2013 19:16:15 GMT
Server: Apache
Pragma: no-cache
Content-Length: 1808
Vary: User-Agent
Content-Type: application/xml

<?xml version="1.0"?>
<TrackResponse><Response><TransactionReference<XpciVersion>1.0</XpciVersion>         </TransactionReference> <ResponseStatusCode>1</ResponseStatusCode>  <ResponseStatusDescription>Success</ResponseStatusDescription></Response><Shipment> <Shipper><ShipperNumber>975522</ShipperNumber><Address><AddressLine1>1700 SUNFLOWER AVE</AddressLine1><City>COSTA MESA</City><StateProvinceCode>CA</StateProvinceCode><PostalCode>92626   1505</PostalCode><CountryCode>US</CountryCode></Address></Shipper><ShipTo><Address><City>MOUNTAINSIDE</City><StateProvinceCode>NJ</StateProvinceCode><PostalCode>07092</PostalCode><CountryCode>US</CountryCode></Address></ShipTo><Service><Code>002</Code><Description>2ND DAY AIR</Description></Service><ReferenceNumber><Code>01</Code><Value>365357</Value></ReferenceNumber><ReferenceNumber><Code>01</Code><Value>4500137238</Value></ReferenceNumber><ShipmentIdentificationNumber>1Z9755220249869083</ShipmentIdentificationNumber><PickupDate>20130213</PickupDate><Package><TrackingNumber>1Z9755220249869083</TrackingNumber><Activity><ActivityLocation><Address><City>MOUNTAINSIDE</City><StateProvinceCode>NJ</StateProvinceCode><PostalCode>07092</PostalCode><CountryCode>US</CountryCode></Address><Code>M5</Code><Description>MAIL ROOM</Description><SignedForByName>SALEMI</SignedForByName></ActivityLocation><Status><StatusType><Code>D</Code><Description>DELIVERED</Description></StatusType><StatusCode><Code>KB</Code></StatusCode></Status><Date>20130215</Date><Time>093400</Time></Activity><PackageWeight><UnitOfMeasurement><Code>LBS</Code></UnitOfMeasurement><Weight>27.00</Weight></PackageWeight><ReferenceNumber><Code>01</Code><Value>365357</Value></ReferenceNumber><ReferenceNumber><Code>01</Code><Value>4500137238</Value></ReferenceNumber></Package></Shipment></TrackResponse>     --><pre>Array
(
[XPCIVERSION] => 1.0
[RESPONSESTATUSCODE] => 1
[RESPONSESTATUSDESCRIPTION] => Success
[SHIPPERNUMBER] => 975522
[ADDRESSLINE1] => 1700 SUNFLOWER AVE
[CITY] => MOUNTAINSIDE
[STATEPROVINCECODE] => NJ
[POSTALCODE] => 07092
[COUNTRYCODE] => US
[CODE] => 01
[DESCRIPTION] => 2ND DAY AIR
[VALUE] => 4500137238
[SHIPMENTIDENTIFICATIONNUMBER] => 1Z9755220249869083
[PICKUPDATE] => 20130213
[TRACKINGNUMBER] => 1Z9755220249869083
[ACTIVITYLOCATION] => Array
    (
        [ADDRESS] => Array
            (
                [CITY] => MOUNTAINSIDE
                [STATEPROVINCECODE] => NJ
                [POSTALCODE] => 07092
                [COUNTRYCODE] => US
            )

        [CODE] => M5
        [DESCRIPTION] => MAIL ROOM
        [SIGNEDFORBYNAME] => SALEMI
    )

[STATUS] => Array
    (
        [STATUSTYPE] => Array
            (
                [CODE] => D
                [DESCRIPTION] => DELIVERED
            )

        [STATUSCODE] => Array
            (
                [CODE] => KB
            )

    )

[DATE] => 20130215
[TIME] => 093400
[UNITOFMEASUREMENT] => Array
    (
        [CODE] => LBS
    )

[WEIGHT] => 27.00
)

1 个答案:

答案 0 :(得分:0)

听起来你拥有所需的一切。解析结果,读入电子邮件地址列表,然后将它们插入数据库(首先仔细检查重复项)。

该阵列看起来很容易访问。它只是一个简单的"INSERT INTO ... VALUES( $array['DATE'], $array['TIME'] ...)"

这是PHP中PDO的一个很好的介绍:http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html#7.1