2013-07-22 7 views
0

XML 피드를 대량로드하고 데이터베이스에 정보를 저장해야합니다. XML 필드를 제어 할 수는 없지만 일반적으로 고유 ID, 제목, 통화, 가격 및 기간이 포함됩니다.데이터베이스의 XML 태그

아래 코드는 단지 한 공급을 위해 잘 작동 :

function process_xml_file($path, $adv_id) 
{ 

$xml = simplexml_load_file($path, 'SimpleXMLElement', LIBXML_NOCDATA); 

$data = array(); 
$finished = array(); 
$counter = 0; 

// loop through all items 
foreach($xml->product as $product) 
{ 
    $product_id = strip_tags((string)$product->productID); 

    if(!in_array($product_id, $finished)) 
    { 
     $country = $product->xpath('./extra/field[@name="country"]'); 
     $data[$counter]['country'] = strip_tags((string)$country[0]); 

     $data[$counter]['title'] = strip_tags((string)$product->name); 
     $data[$counter]['currency'] = strip_tags((string)$product->price['currency']); 
     $data[$counter]['price'] = strip_tags((string)$product->price); 

     $duration = $product->xpath('./extra/field[@name="duration"]'); 
     $data[$counter]['duration'] = strip_tags((string)$duration[0]); 

     // add this product to the finished array, we want to exclude duplicates 
     $finished[$counter] = $product_id; 

     $counter++; 
    } 
} 
return $data; // the data will be saved to database in an other method 

}

내가 prod_id 및 XPath는 ('./ 추가/필드 [@ 이름 = "국가"같은 것들을 저장하는 생각 ] ')를 데이터베이스에 저장하여 eval()을 사용하여 다른 피드 필드의 값을 쉽게 검색 할 수 있습니다. 나는 eval()이 나쁘다는 것을 알고 더 나은 제안을하기 위해 열심히 노력하고있다. 나는이 종류의 데이터를 처리하는 유일한 사람이다. 그래서 eval() 위험은 평소보다 약간 작을 수있다.

Parse error: syntax error, unexpected '"xpath('./additional/field[@na' (T_CONSTANT_ENCAPSED_STRING), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in C:\xampp\htdocs\project\feed.php(220) : eval()'d code on line 1 

예 :

// simple xml object of all products 
$children = $xml->children(); 

$country = $tag['country']; // $tag is from the db 

// loop through all products 
foreach($children as $product) 
{ 
    $id = strip_tags($product->$product_id); 

    $country = $product->$country; 
    eval("\$country2 = \$product->\"{$country}\";"); 

    echo $country2; 
} 

내 데이터베이스 테이블

PRODUCT_ID를 검색 및 제목이 잘 작동, 문제는 국가 및 기간과 같은 오류가 발생합니다 XPath는, 평가를()를 사용하여에 :

CREATE TABLE IF NOT EXISTS `tbl_feeds_xml_tags` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `feed_id` int(11) NOT NULL, 
    `country` varchar(100) COLLATE utf8_unicode_ci NOT NULL, 
    `product_id` varchar(100) COLLATE utf8_unicode_ci NOT NULL, 
    `title` varchar(100) COLLATE utf8_unicode_ci NOT NULL, 
    `currency` varchar(100) COLLATE utf8_unicode_ci NOT NULL, 
    `price` varchar(100) COLLATE utf8_unicode_ci NOT NULL, 
    `duration` varchar(100) COLLATE utf8_unicode_ci NOT NULL, 
    PRIMARY KEY (`id`), 
    KEY `feed_id` (`feed_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; 

Array 
(
    [id] => 1 
    [feed_id] => 1 
    [country] => xpath('./additional/field[@name="country"]') 
    [product_id] => productID 
    [title] => name 
    [currency] => price['currency'] 
    [price] => price 
    [duration] => xpath('./additional/field[@name="duration"]') 
) 

XML 피드 예 :

<?xml version="1.0" encoding="iso-8859-1"?> 
<products> 
    <product> 
    <productID>32934</productID> 
    <name>Cruise Antillen en Zuid-Amerika &amp; strand Curaçao</name> 
    <price currency="EUR">1405.00</price> 
    <extra> 
     <field name="country">Panama</field> 
     <field name="duration">12</field> 
    </extra> 
    </product> 
    .. 
    etc. 
    .. 
</products> 

내 질문은 : 어떻게 모든 피드에 대해이 기능을 작동 할 수 있습니까? 다른 피드에서는 prod_id 또는 country 태그의 이름이 완전히 다른 것을 명심하십시오.

나는 이것을 이해할 수없고 며칠 동안 고생했으며이 포럼에서 답변을 찾지 못했습니다.

eval() 대안 제안도 환영합니다.

저는 PHP의 초보자이기 때문에 답변을 명확히하십시오.

+0

결과는 $ array [$ feed [ 'value_being_fetched']] 때문입니다. 고유 ID (예 : XML 파일의 productID)를 사용하여 모든 결과를 깔끔하게 정렬하기 위해 $ 배열을 어떻게 변경할 수 있습니까? – Soundz

답변

0

왜 eval()이 필요한가요? 각 피드에 필요한 값을 검색하는 xpath 표현식을 저장하는 경우 해당 표현식을 검색하여 DOM 시스템에 전달하면됩니다.

데이터베이스 :

feeds (id, url) 
feed_xpath (id, feed_id, value_being_fetched, xpath_expression) 

특정 피드를 당겨, 예를 들어, http://example.com/feed.xml 후 관련 XPath는 물건을 올려 :

이 당신이
+0

감사 @Marc B. 난 당신의 코드가 작동있어 원하는 것을 내가 아직 도착하지 말아 텍스트의 벽이지만, 그것은 단지의 1 개 행을 반환하더라도

$dom = new DOMDocument(); $dom->loadHTML($feed_url); $xpath = new DOMXPath($dom); $values = array(); foreach($feeds as $feed) { // $feeds being selected from the feeds_xpath table $nodelist = $xpath->query($feed['xpath']) foreach($nodelist as $node) { $array[$feed['value_being_fetched']] = $node->nodeValue; } }