Good afternoon, I am making a module for Magento, I need help to connect it to an external API, essentially the channeladvisor API, and make some requests to this API, here my Module Code... I need to synchronize my inventory in channel advisor in my store made in magento
Config XML
<?xml version="1.0"?>
<!--
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_ImportExport:etc/import.xsd">
<entity name="CA_Import" label="Customer Group" model="Ibnab\Tutie\Model\Import\CustomerGroup" behaviorModel="Magento\ImportExport\Model\Source\Import\Behavior\Basic" />
</config>
Itegration XML
<integration name="TestIntegration">
<resources>
<!-- To grant permission to Magento_Log::online, its parent Magento_Customer::customer needs to be declared as well-->
<resource name="Magento_Customer::customer" />
<resource name="Magento_Log::online" />
<!-- To grant permission to Magento_Sales::reorder, all its parent resources need to be declared-->
<resource name="Magento_Sales::sales" />
<resource name="Magento_Sales::sales_operation" />
<resource name="Magento_Sales::sales_order" />
<resource name="Magento_Sales::actions" />
<resource name="Magento_Sales::reorder" />
</resources>
</integration>
i wanna implement this php consult in mi module:
PHP Code:
<?php
//Initialize test variables
$sku='zz-cf002-e';
$title='Game Set';
$subtitle='';
$shortdescription='Some Descriptive Text';
$description='More Descriptive Text';
$weight=1.1;
$total=14;
$cost=99;
$retailprice=99;
$startingprice=99;
$takeItprice=99;
$secondchanceofferprice=99;
$storeprice=99;
$classname='mahjong';
$attname1='Bullet_List';
$attvalue1='A list of bullet points';
$attname2='SHIPPING_BESTRATE';
$attvalue2='11.77';
$attname3='SHIPPING_BESTRATESERVICE';
$attvalue3='UPS Ground';
$image1='ZZ-CF002-E_a.jpg';
$image2='ZZ-CF002-E_b.jpg';
$image3='ZZ-CF002-E_c.jpg';
$image4='ZZ-CF002-E_d.jpg';
$usa_48_ups_ground=10;
$usa_48_ups_ground_2=7;
$usa_48_ups_2day=30;
$usa_48_ups_2day_2=15;
//Create the XML set
require_once('nusoap.php');
$client = new soapclient_xxx('https://api.channeladvisor.com/
ChannelAdvisorAPI/v1/inventoryService.asmx?WSDL', true );
$err = $client->getError();
if ($err)
{
echo 'Constructor error' . $err . '';
}
$developerKey = 'XXX';
$password = 'XXX';
$headers = '<APICredentials xmlns="http://api.channeladvisor.com/
webservices/">
<DeveloperKey>'.$developerKey.'</DeveloperKey>
<Password>'.$password.'</Password>
</APICredentials> ';
$arrData = array('accountID'=>'XXX',
'item'=>array(
'Sku'=>$sku,
'Title'=>$title,
'Subtitle'=>$subtitle,
'ShortDescription'=>$shortdescription,
'Description'=>$description,
'Weight'=>$weight,
'QuantityInfo'=>array(
'UpdateType'=>'Absolute', 'Total'=>$total),
'PriceInfo'=>array(
'Cost'=>number_format($cost, 2),
'RetailPrice'=>number_format($retailprice, 2),
'StartingPrice'=>number_format($startingprice, 2),
'ReservePrice'=>0,
'TakeItPrice'=>number_format($takeItprice, 2),
'SecondChanceOfferPrice'=>number_format($secondchanceofferprice, 2),
'StorePrice'=>number_format($storeprice, 2)),
'ClassificationInfo'=>array(
'Name'=>$classname, 'AttributeList'=>array(
'ClassificationAttributeInfo___1'=>array(
'Name'=>$attname1, 'Value'=>$attvalue1),
'ClassificationAttributeInfo___2'=>array(
'Name'=>$attname2, 'Value'=>$attvalue2),
'ClassificationAttributeInfo___3'=>array(
'Name'=>$attname3, 'Value'=>$attvalue3))),
'ImageList'=>array(
'ImageInfoSubmit___1'=>array(
'PlacementName'=>'ITEMIMAGEURL1',
'FilenameOrUrl'=>$image1),
'ImageInfoSubmit___2'=>array(
'PlacementName'=>'ITEMIMAGEURL2',
'FilenameOrUrl'=>$image2),
'ImageInfoSubmit___3'=>array(
'PlacementName'=>'ITEMIMAGEURL3',
'FilenameOrUrl'=>$image3),
'ImageInfoSubmit___4'=>array(
'PlacementName'=>'ITEMIMAGEURL4',
'FilenameOrUrl'=>$image4)),
'ShippingInfo'=>array(
'DistributionCenterCode'=>'Alhambra', 'ShippingRateList' =>array(
'ShippingRateInfo___1'=>array(
'DestinationZoneName'=>'USA48',
'CarrierCode'=>'* UPS',
'ClassCode'=>'GROUND',
'FirstItemRate'=>$usa_48_ups_ground,
'AdditionalItemRate'=>$usa_48_ups_ground_2,
'FirstItemHandlingRate'=>0,
'AdditionalItemHandlingRate'=>0,
'FreeShippingIfBuyItNow'=>'false',
'FirstItemRateAttribute'=>'Price',
'AdditionalItemRateAttribute'=>'Price'),
'ShippingRateInfo___2'=>array(
'DestinationZoneName'=>'USA48',
'CarrierCode'=>'UPS',
'ClassCode'=>'2DAY',
'FirstItemRate'=>$usa_48_ups_2day,
'AdditionalItemRate'=>$usa_48_ups_2day_2,
'FirstItemHandlingRate'=>0,
'AdditionalItemHandlingRate'=>0,
'FreeShippingIfBuyItNow'=>'false',
'FirstItemRateAttribute'=>'Price',
'AdditionalItemRateAttribute'=>'Price'))),
));
//fix repeating fields prior to send (eliminate ___1, ___2, etc.)
function array2xml($arrData, $level) {
$xml = '';
foreach( $arrData as $key => $value ) {
$spacer = '';
for ($i = 0; $i < $level; $i++) { $spacer .= "\t"; }
if ( is_array( $value ) ) {
if (preg_match("/^(.+)___\d+$/", $key, $m)) {
$xml .= $spacer . "<" . $m[1] . ">\n" . array2xml($value, $level
+1) . $spacer . "</" . $m[1] . ">\n";
} else {
$xml .= $spacer . "<" . $key . ">\n" . array2xml($value, $level
+1) . $spacer . "</" . $key . ">\n";
}
} else {
$xml .= $spacer . "<" . $key . ">" . $value . "</" . $key . ">\n";
}
}
return $xml;
}
//apply the function
$cleanedxml = '<SynchInventoryItem xmlns="http://
api.channeladvisor.com/webservices/">' . "\n" .
array2xml($arrData, 0) .
'</SynchInventoryItem>' . "\n";
// Call the SOAP method and send
$result = $client->call('SynchInventoryItem', $cleanedxml, false,
false, $headers);
//Print out the results
if ($client->fault)
{
echo 'Fault';
print_r($result);
echo '';
}
else
{
$err = $client->getError();
if ($err)
{
echo 'Error' . $err . '';
}
else
{
echo 'Result';
print_r($result);
echo '';
}
}
echo "<hr>";
echo '<h2>Request</h2>';
echo '<pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</
pre>';
echo '<h2>Response</h2>';
echo '<pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</
pre>';
?>
I'm working with the youtube v3 api. After a few tests, I realized that I need some help. When I'm trying to display the xml content, I'm just getting null values. Can anybody help me?
If you want to see the xml:
https://www.youtube.com/feeds/videos.xml?channel_id=$channelid
And my code is:
$xml=simplexml_load_file("videos.xml");
foreach($xml as $content) {
echo $content->title . "<br>";
echo $content->link['href'] . "<br>";
}
Xml that I want to display:
<entry>
Video ID <yt:videoId>Q4vSZA_8kYY</yt:videoId>
Video title <title>¡Trailer del canal! CBPrductions</title>
Upload date <published>2016-01-14T07:37:03+00:00</published>
<media:group>
Description <media:description>
LIKE PORQUE LO DIGO YO _ Suscribete!: https://www.youtube.com/user/SpanishCBProductions Dale a LIKE a mi página Facebook: https://www.facebook.com/SpanishCBProductions Sigueme en TWITTER!: https://twitter.com/CcristianN3 Y en mi poco sexy INSTAGRAM: http://instagram.com/ccristiann3/
</media:description>
</media:group>
</entry>
I think you can register the namespace and use xpath.
Then for the 'media' and the 'yt' you can get the children by passing the namespace.
If you want to display the first entry:
$url = 'https://www.youtube.com/feeds/videos.xml?channel_id=UCRGn72Qu0KTtI_ujNxRr3Fg';
$xml = simplexml_load_file($url);
$ns = $xml->getDocNamespaces(true);
$xml->registerXPathNamespace('a', 'http://www.w3.org/2005/Atom');
$elements = $xml->xpath('//a:entry');
$content = $elements[0];
$yt = $content->children('http://www.youtube.com/xml/schemas/2015');
$media = $content->children('http://search.yahoo.com/mrss/');
echo "Video ID: " . $yt->videoId . "<br>";
echo "Video title: " . $content->title . "<br>";
echo "Upload date: " . $content->published . "<br>";
echo "Description: " .$media->group->description . "<br>";
If you want to display the information from all the entries, you can use:
foreach ($elements as $content) {
$yt = $content->children('http://www.youtube.com/xml/schemas/2015');
$media = $content->children('http://search.yahoo.com/mrss/');
echo "Video ID: " . $yt->videoId . "<br>";
echo "Video title: " . $content->title . "<br>";
echo "Upload date: " . $content->published . "<br>";
echo "Description: " . $media->group->description . "<br>";
echo "<br>";
}
I have successfully put together a PHP script to read content of an xml file and output the result to HTML page. The only bit I am struggling with is how to format the output into a table.
PHP Script:
<?php
// Loading the XML file
$xml = simplexml_load_file("ftpxml.xml");
echo "<h2>".$xml->getName()."</h2><br />";
foreach($xml->children() as $ftpxml)
{
echo "PID : ".$ftpxml->attributes()->pid."<br />";
echo "Account : ".$ftpxml->attributes()->account." <br />";
echo "Time : ".$ftpxml->attributes()->time." <br />";
echo "<hr/>";
}
?>
HTML Result:
PID : 279
Account : account001
Time : 137
----------------------------------------------------------------
PID : 268
Account : account002
Time : 301
----------------------------------------------------------------
PID : 251
Account : account003
Time : 5
----------------------------------------------------------------
I am lost as to how to display each table headings and the corresponding contents. I am new to PHP so please guide me or if already answered else where, please provide link so I can learn from it.
Thanks
<?php
// Loading the XML file
$xml = simplexml_load_file("ftpxml.xml");
echo "<h2>".$xml->getName()."</h2><br />";
echo "<table>";
foreach($xml->children() as $ftpxml)
{
echo "<tr><td>PID : ".$ftpxml->attributes()->pid."</td></tr>";
echo "<tr><td>Account : ".$ftpxml->attributes()->account." </td></tr>";
echo "<tr><td>Time : ".$ftpxml->attributes()->time." </td></tr>";
}
echo "</table>";
?>
echo '<table>';
echo '<thead><tr><th>PID</th><th>Account</th><th>Time</th></tr></thead><tbody>';
foreach($xml->children() as $ftpxml)
{
echo '<tr>';
echo "<td>PID : ".$ftpxml->attributes()->pid."</td>";
echo "<td>Account : ".$ftpxml->attributes()->account."</td>";
echo "<td>Time : ".$ftpxml->attributes()->time." </td>";
echo '</tr>';
}
echo '</tbody></table>';
I assume you want to make the different values different fields in the table:
// Loading the XML file
$xml = simplexml_load_file("ftpxml.xml");
echo "<h2>".$xml->getName()."</h2><br />";
echo "<table><thead><tr><th>PID</th><th>Account</th><th>Time</th></tr></thead><tbody>";
foreach($xml->children() as $ftpxml)
{
echo '<tr>';
echo '<td>' . $ftpxml->attributes()->pid . "</td>";
echo '<td>' . $ftpxml->attributes()->account . "</td>";
echo '<td>' . $ftpxml->attributes()->time . "</td>";
echo '</tr>';
}
echo '</tbody></table>';
I'm working on json source from wunderground.com. As the example code displayed in the document. I can adjust and work out for some simple format. But I'm stuck with this one. I tried to googled every where but there's no solution.
Here's the sample codes:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json");
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
?>
Well, I need some information like "Cedar Rapids" out of pws/station :
"pws": {
"station": [
{
"neighborhood":"Ellis Park Time Check",
"city":"Cedar Rapids",
"state":"IA",
"country":"US",
"id":"KIACEDAR22",
"lat":41.981174,
"lon":-91.682632,
"distance_km":2,
"distance_mi":1
}
]
}
(You can get all code by clicking this : http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json )
Now the questions are:
What is this data called? (array, array in array?)
How could I pull this data out of the line?
Regards,
station is an array within the pws object.
To get the data, you can do something like this:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json");
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
$stations = $parsed_json->{'location'}->{'nearby_weather_stations'}->{'pws'}->{'station'};
$count = count($stations);
for($i = 0; $i < $count; $i++)
{
$station = $stations[$i];
if (strcmp($station->{'id'}, "KIACEDAR22") == 0)
{
echo "Neighborhood: " . $station->{'neighborhood'} . "\n";
echo "City: " . $station->{'city'} . "\n";
echo "State: " . $station->{'state'} . "\n";
echo "Latitude: " . $station->{'lat'} . "\n";
echo "Longitude: " . $station->{'lon'} . "\n";
break;
}
}
?>
Output:
Current temperature in Cedar Rapids is: 38.5
Neighborhood: Ellis Park Time Check
City: Cedar Rapids
State: IA
Latitude: 41.981174
Longitude: -91.682632
Wonder if you can help for Christmas.
I am trying to read an XML but am having a few issues, basically the foreach structure isnt letting me return the data in the structure I want, and I am not sure of the correct way of doing this. Example below:
`<event id="298640100" date="Sat Dec 31 16:00:00 CET 2011">
<market id="9064667" type="1" status="Open" period="FT">
<description>Match Betting</description>
<place_terms>Win only</place_terms>
−
<outcome id="6798861400">
<description>Draw</description>
−
<price id="24532283602">
<decimal>3.5</decimal>
<fractional>5/2</fractional>
</price>
<position>2</position>
</outcome>
−
<outcome id="6798861200">
<description>Bolton Wanderers</description>
−
<price id="24532283402">
<decimal>2.0</decimal>
<fractional>1/1</fractional>
</price>
<position>1</position>
</outcome>
−
<outcome id="6798861300">
<description>Wolves</description>
−
<price id="24532283502">
<decimal>3.6</decimal>
<fractional>13/5</fractional>
</price>
<position>3</position>
</outcome>
</market>
</event>`
PHP
`<?php
$source = file_get_contents("vc.xml");
$xml = simplexml_load_string($source);
$game = $xml->xpath("//event");
foreach ($game as $event)
{
echo "<b>Event ID:</b> " . $event['id'] . "<br />";
echo "<b>Event Date:</b> " . $event['date'] . "<br />";
{
foreach ($event->children() as $market)
{
if ($market['period'] == 'FT')
{
foreach ($market->children() as $outcome)
{
echo "<b>Outcome ID:</b> " . $outcome['id'] . "<br />";
foreach ($outcome->children() as $price)
{
echo "<b>Price ID:</b> " . $price ['id'] . "<br />";
foreach ($price->children() as $value)
{
echo "<b>Value:</b> " . $value . "<br />";
}
}
}
}
}
}
echo "<br />";
}
?>`
This is basically returning this:
Event ID: 298640100
Event Date: Sat Dec 31 16:00:00 CET 2011
Outcome ID:
Outcome ID:
Outcome ID: 6798861400
Price ID:
Price ID: 24532283602
Value: 3.5
Value: 5/2
Price ID:
Outcome ID: 6798861200
Price ID:
Price ID: 24532283402
Value: 2.0
Value: 1/1
Price ID:
Outcome ID: 6798861300
Price ID:
Price ID: 24532283502
Value: 3.6
Value: 13/5
Price ID:
Ideally I just want to return the following:
Event ID: 298640100
Event Date: Sat Dec 31 16:00:00 CET 2011
Outcome ID: 6798861400
Price ID: 24532283602
Value: 5/2
Any ideas what I am doing wrong and how I could achieve this.
Thanks in advance
Richard
You have 2 problems here. First, you are using the children() function, which returns all children, not just the specific type you want. This is why you get Outcome ID: 3 times in the begining. Instead of foreach ($market->children() as $outcome) you should use foreach ($market->outcome as $outcome).
Second, it seems like you only want the first result. In that case, you shouldn't be using a foreach. the simplexml object is a set of arrays, and you can access an inividual object in the array by its index number. You can get rid of a lot of your code and just grab the first outcome object directly like this:
$xml->event->market->outcome[0]
You might want to read the official simpleXML documentation http://www.php.net/manual/en/simplexml.examples-basic.php
Here is what i think you need:
foreach ($game as $event)
{
echo "<b>Event ID:</b> " . $event['id'] . "<br />";
echo "<b>Event Date:</b> " . $event['date'] . "<br />";
{
foreach ($event->children() as $market)
{
if ($market['period'] == 'FT')
{
foreach ($market->children() as $name => $outcome )
{
if ( $name != "outcome" )
{
continue;
}
echo "<b>Outcome ID: - $name</b> " . $outcome['id'] . "<br />";
foreach ($outcome->children() as $name => $price)
{
if ( $name != "price" )
{
continue;
}
echo "<b>Price ID:</b> " . $price ['id'] . "<br />";
foreach ($price->children() as $name => $value)
{
if ( $name != "fractional" )
{
continue;
}
echo "<b>Value: - $name</b> " . $value . "<br />";
break;
}
}
break;
}
break;
}
}
}
echo "<br />";
}