2016-04-05 3 views
0

Я получил структуру XML, как это:Объединить/переименовать XML с помощью PHP

<OrderLineItems> 
<SKU/> 
<ItemName>ÁFONYÁS FÁNK</ItemName> 
<Quantity>1</Quantity> 
<Price>350</Price> 
<LineTotal>350</LineTotal> 
<Meta/> 
</OrderLineItems> 
<OrderLineItems> 
<SKU/> 
<ItemName>CSIRKE SALÁTA ÖNTETTEL</ItemName> 
<Quantity>1</Quantity> 
<Price>1150</Price> 
<LineTotal>1150</LineTotal> 
<Meta/> 
</OrderLineItems> 

Я хочу, чтобы вывести так:

<basket> 
<item> ->OrderLineItems 
<billitem_code></billitem_code> -> SKU 
<billitem_name></billitem_name> -> this will be the ItemName 
<billitem_amount></billitem_amount> ->Quantity 
<billitem_unitprice></billitem_unitprice> ->Price 
</item> 
</basket> 

мне удалось прочитать XML и вывод некоторых основные линии

$xml -> customer -> name = $orderxml -> Order -> BillingFullName; 

Но я уже не смог пройти заказанных товаров, если есть больше чем 1.

Любые предложения по управлению этим?

Текущий КОД:

<?php 
error_reporting(E_ALL); 
ini_set('display_errors', '1'); 
header("Content-type:text/xml"); 

//Load 
require "apiclass/database.php"; 
define("DEFAULT_XML_FILE",dirname(__FILE__).'/default.xml'); 

//Database 
$db = new Database; 

//get XML 
$order_id = $_GET["order_id"]; 
$order_file = "xml/order_id-".$order_id.".xml"; 

//XML 
$orderxml = simplexml_load_file($order_file); 
$customerid = $orderxml -> Order -> CustomerId; 

$xml = simplexml_load_file(DEFAULT_XML_FILE); 

//Converting loaded XML to output format 
$xml -> customer -> id = $orderxml -> Order -> CustomerId; 
$xml -> orderdate = $orderxml -> Order -> OrderDate; 
$xml -> customer -> name = $orderxml -> Order -> BillingFullName; 
$xml -> customer -> tel = $orderxml -> Order -> BillingPhone; 
$xml -> customer -> address -> postalcode = $orderxml -> Order -> BillingPostCode; 
$xml -> customer -> address -> city = $orderxml -> Order -> BillingCity; 
$xml -> customer -> address -> district = $orderxml -> Order -> BillingState; 
$xml -> customer -> address -> street = $orderxml -> Order -> BillingAddress1; 
$xml -> customer -> address -> number = $orderxml -> Order -> BillingAddress2; 
$xml -> customer -> address -> description = $orderxml -> Order -> CustomerNote; 
$xml -> payment_method = $orderxml -> Order -> ShippingMethod; 

foreach($orderxml -> Order -> OrderLineItems -> ItemName as $key => $value) 
{ 
$xml -> basket -> item -> billitem_name = $value ; 
} 

$xml -> deliveryprice = $orderxml -> Order -> FeeTotal; 
$xml -> totalprice = $orderxml -> Order -> OrderTotal; 
print $xml -> asXML(); 

//Debuggolás 
//echo '<pre>'; 
//var_dump($xml); 
//echo '</pre>'; 
?> 
+0

Пожалуйста показать свой реальный код ... Мы можем помочь вам повышение его – Random

+0

я обновленный с током код. Я полностью не понимаю, как идти, хотя те -s, если их больше 1. –

+0

Проверьте 'SimpleXMLElement :: addChild()'. Но я предлагаю прочитать о XSLT. Это язык, специфический для преобразования документов XML. PHP поддерживает его через ext/xsl. – ThW

ответ

0

Самый прекрасный способ превратить ваш XML, вероятно XSLT, язык для преобразования XML-документов в другие документы XML. Также DOMDocument более мощный, чем SimpleXML для узлов импорта/преобразования.

С помощью SimpleXML вы можете использовать ->addChild(name,value)->addChild(name,value)->....

В противном случае вы можете использовать трюк . Разделить шаблон назначения XML в двух частях:

$xmlDefault ='<?xml version="1.0" encoding="utf-8"?> 
<basket/>'; 

$itemTemplate = '<item> 
<billitem_code></billitem_code> 
<billitem_name></billitem_name> 
<billitem_amount></billitem_amount> 
<billitem_unitprice></billitem_unitprice> 
</item> 
'; 

Загрузите исходный XML файл:

$orderxml  = simplexml_load_file($order_file); 

Выберите <OrderLineItems> элементы:

$orderLineItems = $orderxml->OrderLineItems; 

А затем создать новый XML-адресат же <item> номер $orderLineItems:

$newXml = "<basket>\n".str_repeat($itemTemplate, count($orderLineItems))."</basket>"; 
$xml = simplexml_load_string($newXml); 

Теперь вы можете добавить каждый узел:

$key = 0; 
foreach($orderLineItems as $node) 
{ 
    $xml->item[$key]->billitem_code  = $node->SKU; 
    $xml->item[$key]->billitem_name  = $node->ItemName; 
    $xml->item[$key]->billitem_amount = $node->Quantity; 
    $xml->item[$key]->billitem_unitprice = $node->Price; 
    $key++; 
} 

$xml конечного содержание:

<basket> 
    <item> 
     <billitem_code></billitem_code> 
     <billitem_name>ÁFONYÁS FÁNK</billitem_name> 
     <billitem_amount>1</billitem_amount> 
     <billitem_unitprice>350</billitem_unitprice> 
    </item> 
    <item> 
     <billitem_code></billitem_code> 
     <billitem_name>CSIRKE SALÁTA ÖNTETTEL</billitem_name> 
     <billitem_amount>1</billitem_amount> 
     <billitem_unitprice>1150</billitem_unitprice> 
    </item> 
</basket> 
+0

THX MAN! С помощью нескольких трюков мне удалось это сделать! –

Смежные вопросы