2016-08-18 3 views
1

Я пытаюсь проанализировать XML-ответ от ebay для finditem api с php. Вот мой код:Как разобрать ответ ebay xml с php

<head> 
    <title>Title</title> 
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> 
    <meta content="utf-8" http-equiv="encoding"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
</head> 
<body> 
<? 

$pagenumber = 1; 
$keyword = 'iphone'; 
$entriesperpage = 1; 
$ebayusername = 'ebay-username-here'; 

$response = getFindProducts($keyword, $ebayusername, $entriesperpage); 
echo '<div style="display: none;">' . $response . '</div>'; 

$xmlResponse = new SimpleXMLElement($response); 
echo $xmlResponse -> searchresult -> item[0] -> title; 

function getFindProducts($keyword,$ebayusername,$entriesperpage) { 

$xmlRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; 
$xmlRequest .= '<findItemsAdvancedRequest xmlns="http://www.ebay.com/marketplace/search/v1/services">'; 
$xmlRequest .= '<keywords>' . $keyword . '</keywords>'; 
$xmlRequest .= '<itemFilter>'; 
$xmlRequest .= '<name>Seller</name>'; 
$xmlRequest .= '<value>' . $ebayusername . '</value>'; 
$xmlRequest .= '</itemFilter>'; 
$xmlRequest .= '<paginationInput>'; 
$xmlRequest .= '<entriesPerPage>' . $entriesperpage . '</entriesPerPage>'; 
$xmlRequest .= '</paginationInput>'; 
$xmlRequest .= '</findItemsAdvancedRequest>'; 

// define our header array for the Shopping API call 
$headers = array(
    'X-EBAY-SOA-SECURITY-APPNAME:' . 'appname-here', 
    'X-EBAY-SOA-OPERATION-NAME:findItemsAdvanced' 
); 

// initialize our curl session 
$session = curl_init(FINDING_API_ENDPOINT); 

// set our curl options with the XML request 
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($session, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($session, CURLOPT_POST, true); 
curl_setopt($session, CURLOPT_POSTFIELDS, $xmlRequest); 
curl_setopt($session, CURLOPT_RETURNTRANSFER, true); 

if(curl_exec($session) === false){ echo 'Curl error: ' . curl_error($session); } 

// execute the curl request 
$responseXML = curl_exec($session); 

// close the curl session 
curl_close($session); 

// return the response XML 
return $responseXML; 

} 

?> 
</body> 

</html> 

Когда я бегу, он успешно работает в том, что он действительно получает ответ от Ebay, и я могу видеть структуру продукта XML, если я повторить все, что нужно страницу в исходном коде.

Проблема с раздела:

$xmlResponse = new SimpleXMLElement($response); 
echo $xmlResponse -> searchresult -> item[0] -> title; 

Он не может в автоматическом режиме без каких-либо ошибок. У меня есть сообщение об ошибке.

Любая помощь очень ценится!

--- EDIT ---

Ответ XML-код структурирована следующим образом:

<!--?xml version='1.0' encoding='UTF-8'?--> 
<finditemsadvancedresponse xmlns="http://www.ebay.com/marketplace/search/v1/services"> 
<ack>Success</ack> 
<version>1.13.0</version> 
<timestamp>2016-08-18T19:25:06.303Z</timestamp> 
<searchresult count="1"> 
    <item> 
    <itemid>123456789</itemid> 
    <title>Item Title</title> 
    <globalid>EBAY-US</globalid> 
    <primarycategory> 
     <categoryid>12345</categoryid> 
     <categoryname>Category Name</categoryname> 
    </primarycategory> 
    <galleryurl>Galery URL</galleryurl> 
    <viewitemurl>Item URL</viewitemurl> 
    <paymentmethod>PayPal</paymentmethod> 
    <autopay>false</autopay> 
    <postalcode>12345</postalcode> 
    <location>Location</location> 
    <country>US</country> 
    <shippinginfo> 
     <shippingservicecost currencyid="USD">0.0</shippingservicecost> 
     <shippingtype>Free</shippingtype> 
     <shiptolocations>US</shiptolocations> 
     <expeditedshipping>true</expeditedshipping> 
     <onedayshippingavailable>false</onedayshippingavailable> 
     <handlingtime>1</handlingtime> 
    </shippinginfo> 
    <sellingstatus> 
     <currentprice currencyid="USD">15.99</currentprice> 
     <convertedcurrentprice currencyid="USD">15.99</convertedcurrentprice> 
     <sellingstate>Active</sellingstate> 
     <timeleft>P9DT3H29M13S</timeleft></sellingstatus> 
     <listinginfo> 
     <bestofferenabled>false</bestofferenabled> 
     <buyitnowavailable>false</buyitnowavailable> 
     <starttime>2015-12-01T22:54:19.000Z</starttime> 
     <endtime>2016-08-27T22:54:19.000Z</endtime> 
     <listingtype>FixedPrice</listingtype> 
     <gift>false</gift> 
     </listinginfo> 
     <returnsaccepted>true</returnsaccepted> 
     <condition> 
     <conditionid>3000</conditionid> 
     <conditiondisplayname>Used</conditiondisplayname> 
     </condition> 
     <ismultivariationlisting>false</ismultivariationlisting> 
     <topratedlisting>false</topratedlisting> 
    </item> 
</searchresult> 
<paginationoutput> 
    <pagenumber>1</pagenumber> 
    <entriesperpage>1</entriesperpage> 
    <totalpages>100</totalpages> 
    <totalentries>100</totalentries> 
</paginationoutput> 
<itemsearchurl>http://www.ebay.com/sch/i.html?_sasl=allkillerdeals&amp;_saslop=1&amp;_fss=1&amp;LH_SpecificSeller=1&amp;_nkw=knife&amp;_ddo=1&amp;_ipg=1&amp;_pgn=1</itemsearchurl> 
</finditemsadvancedresponse> 
+2

Вы должны были бы показать фактический/отношение XML. php сам по себе бесполезен без него. –

+2

Можете ли вы опубликовать, как выглядит ответ? – Machavity

+0

Вы должны иметь возможность получить ответ, запустив php с вашими учетными данными ebay. Я не могу изменить ответ xml, он исходит из ebay как есть. – TK421

ответ

0

Наконец взломали. После нескольких часов разочарований, наконец, выяснилось, что xml-эхо-путь равен сенсационный случай. Только в самом скрипте, потому что, когда я скопировал xml (для приведенного выше примера) из исходного кода html, он обнаружил все строчные буквы. Но фактический возвращенный xml имеет смешанный регистр в узлах xml.

Так,

echo $xmlResponse -> searchresult -> item[0] -> title; 

должно быть:

echo $xmlResponse -> searchResult -> item[0] -> title; 
+0

Но ваш опубликованный XML имеет 'searchresult' все строчные буквы, а не camelcase. – Parfait

+0

Это так ... Я скопировал его из исходного кода html на странице, который сделал его все в нижнем регистре. Только когда я напечатал его в текстовом поле и сравнил его с структурой ответа из документации ebay api, я понял, что это камешка. – TK421

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