Отображение XML в качестве ответа в PHP с помощью eBay API

Следуя руководству, показано, как отображать данные в формате HTML на основе что мне просто нужно показать ответ XML, а не анализировать его. Я пытался найти решение, но мне не повезло. Любая помощь будет оценена.

<?php

$endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1';  // URL to call
$query = 'iphone';                  // Supply your own query keywords as needed

// Construct the findItemsByKeywords POST call
// Load the call and capture the response returned by the eBay API
// The constructCallAndGetResponse function is defined below
$resp = simplexml_load_string(constructPostCallAndGetResponse($endpoint, $query));

// Check to see if the call was successful, else print an error
if ($resp->ack == "Success") {
$results = '';  // Initialize the $results variable

// Parse the desired information from the response
foreach($resp->searchResult->item as $item) {
$link  = $item->viewItemURL;
$title = $item->title;

// Build the desired HTML code for each searchResult.item node and append it to $results
$results .= "<tr><td><img src=\"$pic\"></td><td><a href=\"$link\">$title</a></td></tr>";
 }
}
else {  // If the response does not indicate 'Success,' print an error
  $results  = "<h3>Oops! The request was not successful";
  $results .= "AppID for the Production environment.</h3>";
}

function constructPostCallAndGetResponse($endpoint, $query) {
global $xmlrequest;

// Create the XML request to be POSTed
$xmlrequest  = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
$xmlrequest .= "<findItemsByKeywordsRequest                  
xmlns=\"http://www.ebay.com/marketplace/search/v1/services\">\n";
$xmlrequest .= "<keywords>";
$xmlrequest .= $query;
$xmlrequest .= "</keywords>\n";
$xmlrequest .= "<paginationInput>\n 
<entriesPerPage>3</entriesPerPage>\n</paginationInput>\n";
$xmlrequest .= "</findItemsByKeywordsRequest>";

// Set up the HTTP headers
$headers = array(
'X-EBAY-SOA-OPERATION-NAME: findItemsByKeywords',
'X-EBAY-SOA-SERVICE-VERSION: 1.3.0',
'X-EBAY-SOA-REQUEST-DATA-FORMAT: XML',
'X-EBAY-SOA-GLOBAL-ID: EBAY-GB',
'X-EBAY-SOA-SECURITY-APPNAME: ******',
'Content-Type: text/xml;charset=utf-8',
);

$session  = curl_init($endpoint);                       // create a curl session
curl_setopt($session, CURLOPT_POST, true);              // POST request type
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);    // set headers using $headers
 array
curl_setopt($session, CURLOPT_POSTFIELDS, $xmlrequest); // set the body of the POST
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);    //

$responsexml = curl_exec($session);                     // send the request
curl_close($session);                                   // close the session
return $responsexml;                                    // returns a string


}  // End of constructPostCallAndGetResponse function
?>

person user2208358    schedule 25.03.2013    source источник
comment
Можем ли мы увидеть, что вы пробовали до сих пор? Вопросы здесь должны показывать какие-то существенные предшествующие усилия или какой-то неработающий код, чтобы респондентам было с чем поработать. К сожалению, в этом коде нет ни того, ни другого, поэтому в настоящее время он, скорее всего, закрыт.   -  person halfer    schedule 25.03.2013
comment
В учебнике показан код, преобразующий xml в html. Я просто хочу, чтобы он показывал дерево узлов xml.   -  person user2208358    schedule 25.03.2013
comment
ХОРОШО. Тем не менее, сначала попробуйте — у вас уже работает пример?   -  person halfer    schedule 25.03.2013
comment
У меня пример работает нормально. Я попробовал это без включения кода для анализа данных в HTML, но тогда он ничего не отображает.   -  person user2208358    schedule 25.03.2013
comment
Ок, отлично. Давайте посмотрим на код, который у вас есть, без включения кода для анализа данных в HTML (пожалуйста, отредактируйте его в своем вопросе). Я предполагаю, что вам нужно получить результат constructPostCallAndGetResponse() и вывести его на экран, возможно, в htmlentities(), чтобы вы могли видеть угловые скобки.   -  person halfer    schedule 25.03.2013
comment
Опубликовал код, который у меня есть из учебника. Он включает в себя конструкциюPostCallAndGetResponse(). Не уверен, куда идти отсюда   -  person user2208358    schedule 25.03.2013


Ответы (1)


Попробуйте изменить это (завернуто для ясности):

$resp = simplexml_load_string(
    constructPostCallAndGetResponse($endpoint, $query)
);

к этому:

$xmlString = constructPostCallAndGetResponse($endpoint, $query);
$resp = simplexml_load_string($xmlString);
// Now you have your raw XML to play with
echo htmlentities($xmlString);
// The XML document $resp is available too, if you wish to do
// something with that

Оригинал немедленно передает XML-ответ в анализатор XML и создает с ним объект XML (подробности см. в SimpleXML в руководстве по PHP). Здесь мы разделили два вызова, поэтому строка XML теперь сохраняется в промежуточной переменной.

person halfer    schedule 25.03.2013
comment
Это решило мою проблему. Спасибо за вашу помощь и терпение. - person user2208358; 26.03.2013
comment
Можно ли сохранить возвращенный XML в файл XML на сервере? - person user2208358; 26.03.2013