: Invalid argument supplied for foreach() in - php

tried this code on two different WordPress sites. It was working on the first site. After I moved the template completely to my new site, I got this error: Invalid argument supplied for foreach() in
I do not know what is the reason, although it is the same template, plugins and everything
<?php
$novoteste = new ComicLatestChapters("6", "6");
$resultados = $novoteste->filter;
foreach($resultados as $resultado => $novoteste) {
$series_id = $novoteste->post_id;
$status = get_post_status($series_id);
if($status !== 'publish' || $series_id == 20305){
continue;
}
$result = get_post($resultado);
$sort_by = $sort_setting['sortBy'];
$sort_order = $sort_setting['sort'];
$chapters = $wp_manga_functions->get_latest_chapters($series_id, null, 2, 0, $sort_by, $sort_order);
$latest_chapter = $chapters[0];
$semilatest_chapter = $chapters[1];
$scheduled1 = $latest_chapter['schedule_time'];
$scheduled2 = $semilatest_chapter['schedule_time'];
$series_link = get_the_permalink($series_id);
$chapter_slug1 = $latest_chapter['chapter_slug'];
$chapter_slug2 = $semilatest_chapter['chapter_slug'];
$type = $wp_manga_functions->get_manga_type( $manga_id );
$chapter_name1 = $latest_chapter['chapter_name'];
$chapter_name2 = $semilatest_chapter['chapter_name'];
$mass_released = is_mass_released($series_id);
$ch_1 = get_only_numbers($chapter_name1);
$ch_2 = get_only_numbers($chapter_name2);
$rating = get_post_meta($series_id, '_manga_avarage_reviews', true);
$chapter_index1 = $latest_chapter['chapter_index'];
$chapter_index2 = $semilatest_chapter['chapter_index'];
$link1 = $wp_manga_functions->build_chapter_url($series_id, $chapter_slug1);
$link2 = $wp_manga_functions->build_chapter_url($series_id, $chapter_slug2);
$restored = get_post_meta($series_id, 'restored', true);
$publish = $latest_chapter['date'];
$publish2 = $semilatest_chapter['date'];
$type = get_post_meta($series_id, '_wp_manga_chapter_type', true);
$series_status = get_post_meta($series_id, '_wp_manga_status', true);
if (isset($scheduled1)){
$published = $wp_manga_functions->get_time_diff($scheduled1);}
else{
$published = $wp_manga_functions->get_time_diff($publish);
}
if (isset($scheduled2)){
$published2 = $wp_manga_functions->get_time_diff($scheduled2);}
else{
$published2 = $wp_manga_functions->get_time_diff($publish2);
}
$series_class = get_post_meta($series_id, 'manga_custom_badges', true);
$class_css = str_replace(' ', '-', strtolower($series_class));
$novel1 = get_post($series_id);
$title = $novel1->post_title;
$description = $result->post_content;
$thumbnail_id = get_post_meta($series_id, '_thumbnail_id', true);
$thumbnail_link = get_the_post_thumbnail_url($series_id, array(290,395));
?>

You should check that the output $resultados = $novoteste->filter; Is it empty or not?
The code changes like this:
<?php
$novoteste = new ComicLatestChapters( "6", "6" );
$resultados = $novoteste->filter ?: array();
foreach( $resultados as $resultado => $novoteste ) {
........
}

Related

Opencart foreach showing NULL in tpl file

Am creating a custom module in my store using Opencart, that file name called sales_performance.
Here am passing the values for selected customer id and name.
All working fine. when am using var_dump($data['customers']); in controller it showing some values in top of the sales_performance.tpl.
But in sales_performance.tpl am using var_dump($customers); it showing NULL.
sales_performance.php(controller)
<?php
class ControllerProductSalesPerformance extends Controller
{
private $error = array();
public function index()
{
$this->load->language('product/allproduct');
$this->document->setTitle($this->language->get('Sales Performance'));
$this->load->model('catalog/allproduct');
$this->getSelectedCustomer();
$data['text_list'] = $this->language->get('text_list');
$data['text_no_results'] = $this->language->get('text_no_results');
$data['text_confirm'] = $this->language->get('text_confirm');
$data['text_missing'] = $this->language->get('text_missing');
$data['column_order_id'] = $this->language->get('column_order_id');
$data['column_customer'] = $this->language->get('column_customer');
$data['column_status'] = $this->language->get('column_status');
$data['column_total'] = $this->language->get('column_total');
$data['column_date_added'] = $this->language->get('column_date_added');
$data['column_date_modified'] = $this->language->get('column_date_modified');
$data['column_action'] = $this->language->get('column_action');
$data['entry_return_id'] = $this->language->get('entry_return_id');
$data['entry_order_id'] = $this->language->get('entry_order_id');
$data['entry_customer'] = $this->language->get('entry_customer');
$data['entry_order_status'] = $this->language->get('entry_order_status');
$data['entry_total'] = $this->language->get('entry_total');
$data['entry_date_added'] = $this->language->get('entry_date_added');
$data['entry_date_modified'] = $this->language->get('entry_date_modified');
$data['button_invoice_print'] = $this->language->get('button_invoice_print');
$data['button_shipping_print'] = $this->language->get('button_shipping_print');
$data['button_add'] = $this->language->get('button_add');
$data['button_edit'] = $this->language->get('button_edit');
$data['button_delete'] = $this->language->get('button_delete');
$data['button_filter'] = $this->language->get('button_filter');
$data['button_view'] = $this->language->get('button_view');
//$data['token'] = $this->session->data['token'];
$pagination = new Pagination();
//$pagination->total = $order_total;
//$pagination->page = $page;
$data['pagination'] = $pagination->render();
$data['sort'] = $sort;
$data['order'] = $order;
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('default/template/product/sales_performance.tpl', $data));
}
public function getSelectedCustomer()
{
$isSalesPerson=$_COOKIE['isSalesPerson'];
if($isSalesPerson =='true')
{
$selectedCustomerId = $_GET['selectedCustomerId'];
$selectedCustomerName = $_GET['selectedCustomerName'];
}
//select customer
$customerId=$_COOKIE['customerId'];
$query = $this->db->query("select customer_id,CONCAT(c.firstname,' ', c.lastname) as name from " . DB_PREFIX . "customer c where c.sales_person_id=".$customerId." and customer_id=".$selectedCustomerId."");
$getcustomers=$query->rows;
foreach ($getcustomers as $customer) {
$data['customers'][] = array(
'customer_id' => $customer['customer_id'],
'name' => $customer['name']
);
}
var_dump($data['customers']); // this the code showing some value
//select customer
}
}
sales_performance.tpl
<?php var_dump($customers); ?>
<?php foreach ($customers as $customer) { ?>
<h3>Customer ID: <?php echo $customer['customer_id']; ?></h3>
<h3>Customer Name:</h3>
<?php } ?>
What am missed here...?
And Thanks for advance...
The data variable is a variable in your function, you are able to create a protected variable in your class and use that one.
<?php
class ControllerProductSalesPerformance extends Controller
{
private $error = array();
private $data = array();
public function index()
{
$this->load->language('product/allproduct');
$this->document->setTitle($this->language->get('Sales Performance'));
$this->load->model('catalog/allproduct');
$this->getSelectedCustomer();
$this->data['text_list'] = $this->language->get('text_list');
$this->data['text_no_results'] = $this->language->get('text_no_results');
$this->data['text_confirm'] = $this->language->get('text_confirm');
$this->data['text_missing'] = $this->language->get('text_missing');
$this->data['column_order_id'] = $this->language->get('column_order_id');
$this->data['column_customer'] = $this->language->get('column_customer');
$this->data['column_status'] = $this->language->get('column_status');
$this->data['column_total'] = $this->language->get('column_total');
$this->data['column_date_added'] = $this->language->get('column_date_added');
$this->data['column_date_modified'] = $this->language->get('column_date_modified');
$this->data['column_action'] = $this->language->get('column_action');
$this->data['entry_return_id'] = $this->language->get('entry_return_id');
$this->data['entry_order_id'] = $this->language->get('entry_order_id');
$this->data['entry_customer'] = $this->language->get('entry_customer');
$this->data['entry_order_status'] = $this->language->get('entry_order_status');
$this->data['entry_total'] = $this->language->get('entry_total');
$this->data['entry_date_added'] = $this->language->get('entry_date_added');
$this->data['entry_date_modified'] = $this->language->get('entry_date_modified');
$this->data['button_invoice_print'] = $this->language->get('button_invoice_print');
$this->data['button_shipping_print'] = $this->language->get('button_shipping_print');
$this->data['button_add'] = $this->language->get('button_add');
$this->data['button_edit'] = $this->language->get('button_edit');
$this->data['button_delete'] = $this->language->get('button_delete');
$this->data['button_filter'] = $this->language->get('button_filter');
$this->data['button_view'] = $this->language->get('button_view');
//$data['token'] = $this->session->data['token'];
$pagination = new Pagination();
//$pagination->total = $order_total;
//$pagination->page = $page;
$data['pagination'] = $pagination->render();
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['header'] = $this->load->controller('common/header');
$this->data['column_left'] = $this->load->controller('common/column_left');
$this->data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('default/template/product/sales_performance.tpl', $this->data));
}
public function getSelectedCustomer()
{
$isSalesPerson=$_COOKIE['isSalesPerson'];
if($isSalesPerson =='true')
{
$selectedCustomerId = $_GET['selectedCustomerId'];
$selectedCustomerName = $_GET['selectedCustomerName'];
}
//select customer
$customerId=$_COOKIE['customerId'];
$query = $this->db->query("select customer_id,CONCAT(c.firstname,' ', c.lastname) as name from " . DB_PREFIX . "customer c where c.sales_person_id=".$customerId." and customer_id=".$selectedCustomerId."");
$getcustomers=$query->rows;
foreach ($getcustomers as $customer) {
$this->data['customers'][] = array(
'customer_id' => $customer['customer_id'],
'name' => $customer['name']
);
}
var_dump($this->data['customers']); // this the code showing some value
//select customer
}
}
You are also able to let getSelectedCustomer() return an array with the customers, this would be the normal way to do it. I would recomment it to put it into a model as well.

OTA XML standard: error on line 2 at column 1: Extra content at the end of the document XML to get POST in PHP

I have two days trying to fix this error with this XML code:
`<OTA_VehResRQ Version="1.00">
<POS>
<Source><RequestorID ID="22" Type="90"></RequestorID></Source>
</POS>
<BookingReferenceID>
<UniqueID_Type ID="338964670"></UniqueID_Type>
</BookingReferenceID>
<VehResRQCore>
<VehRentalCore PickUpDateTime="2017-01-10T10:00:00" ReturnDateTime="2017-01-11T16:00:00">
<PickUpLocation LocationCode="88" ExtendedLocationCode="CUN01"></PickUpLocation>
<ReturnLocation LocationCode="89" ExtendedLocationCode="CUN"></ReturnLocation>
</VehRentalCore>
<VehPref VendorCarType="MCMR">
<VehClass>MCMR</VehClass>
<VehType>Chevrolet Matiz</VehType>
</VehPref>
<RateQualifier VendorRateID="90" RateAuthorizationCode="51 || 52" PromotionCode=""/>
<Customer>
<Primary>
<PersonName>
<NamePrefix>Mr</NamePrefix>
<GivenName>Carlos</GivenName>
<Surname>Gomez</Surname>
</PersonName>
<Telephone PhoneTechType="001.PTT" PhoneNumber="01 123 4567"></Telephone>
<Telephone PhoneTechType="005.PTT" PhoneNumber="041 234 5678"></Telephone>
<Email>
<Value>xmlbooking#somedomain.com</Value>
</Email>
<Address>
<CityName>Cancun</CityName>
<StateProv>Quintana Roo</StateProv>
<CountryName>New Zealand</CountryName>
</Address>
</Primary>
</Customer>
<Fees>
<Fee Description="10% Airport fee" Purpose="049.VCP" Amount=""></Fee>
</Fees>
<VehicleCharges Purpose="022.VCP">
<VehicleCharge CurrencyCode="USD" >
<Calculation Quantity="4" UnitName="Day" UnitCharge="120" total="480"></Calculation>
<TaxAmounts>
<TaxAmount Description="IVA Tax" TaxCode="IVA" Total=""></TaxAmount>
</TaxAmounts>
</VehicleCharge>
</VehicleCharges>
<TPA_Extensions>
<SOE_ExtrasRequest>
<Extra Code="1" Quantity="1" Amount="26.25" Period="11"></Extra>
<Extra Code="2" Quantity="1" Amount="37.50" Period="NA"></Extra>
<Extra Code="3" Quantity="1" Amount="90" Period="NA"></Extra>
</SOE_ExtrasRequest>
<SOE_Comments>
<Comment Name="optional info 1">
<Text>Any other relevant information such as flight no</Text>
</Comment>
</SOE_Comments>
</TPA_Extensions>
</VehResRQCore>
<SpecificFlightInfoType>
<FlightNumber>123</FlightNumber>
<Airline>British airline</Airline>
</SpecificFlightInfoType>
</OTA_VehResRQ>
`
I'm reading with this method:
`public function actionIndex()
{
if (isset($_REQUEST["XML"])) {
$XML = $_REQUEST["XML"];
} else {
$XML = file_get_contents('php://input');
}
$xmlValidado = XMLReader::xml($XML);
$xmlValidado->setParserProperty(XMLReader::VALIDATE, true);
//header("Content-type: text/xml");
require_once("Array2XML.php");
if ($XML = simplexml_load_string($XML)) {
$Action = $XML->getName();
$POS = $XML->POS;
$Type = $POS->Source->RequestorID->attributes()->Type;
$UserName = $POS->Source->RequestorID->attributes()->ID;
$Password = $POS->Source->RequestorID->attributes()->MessagePassword;
header("Content-type: text/xml");
$this->{$Action}($XML);
} else {
header("Content-type: text/xml");
$Results = array();
$Results['#attributes'] = array(
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'lastUpdated' => date('c'),
);
$Results["ErrorMessage"] = utf8_encode("XML Invalido!");
$xml = Array2XML::createXML('Error', $Results);
echo str_replace("\n", "", (trim($xml->saveXML())));
}
exit();
}`
And I load a method called:
public function OTA_VehResRQ($XML){
$Results = array();
$Results['#attributes'] = array(
'Version' => '1.00',
'TimeStamp' => date('c')
);
$ctTextLoc = self::CT_TEXTLOC;
$ctLocations = self::CT_LOCATIONS;
$ctEstatus = self::CT_ST;
$RateId = (int)$XML->POS->Source->RequestorID->attributes()->ID;
$DateIn = (string)$XML->VehResRQCore->VehRentalCore->attributes()->PickUpDateTime;
$DateOut = (string)$XML->VehResRQCore->VehRentalCore->attributes()->ReturnDateTime;
$locpu_text = (string)$XML->VehResRQCore->VehRentalCore->PickUpLocation->attributes()->ExtendedLocationCode;
$locdo_text = (string)$XML->VehResRQCore->VehRentalCore->ReturnLocation->attributes()->ExtendedLocationCode;
$salutation = (string)$XML->VehResRQCore->Customer->Primary->PersonName->NamePrefix;
$nombre = (string)$XML->VehResRQCore->Customer->Primary->PersonName->GivenName;
$apellidos = (string)$XML->VehResRQCore->Customer->Primary->PersonName->Surname;
$email = (string)$XML->VehResRQCore->Customer->Primary->Email;
$telefono = ((string)$XML->VehResRQCore->Customer->Primary->Telephone->attributes()->PhoneTechType == '001.PTT')?(string)$XML->VehResRQCore->Customer->Primary->Telephone->attributes()->PhoneNumber : '';
$ciudad = (string)$XML->VehResRQCore->Customer->Primary->Address->CityName;
$celular = ((string)$XML->VehResRQCore->Customer->Primary->Telephone->attributes()->PhoneTechType == '005.PTT')?(string)$XML->VehResRQCore->Customer->Primary->Telephone->attributes()->PhoneNumber : '';
$estado = (string)$XML->VehResRQCore->Customer->Primary->Address->StateProv;
$pais = (string)$XML->VehResRQCore->Customer->Primary->Address->CountryName;
$datePickup = date("Y-m-d", strtotime($DateIn));
$dateDropoff = date("Y-m-d", strtotime($DateOut));
$referencia = (string)$XML->BookingReferenceID->UniqueID_Type->attributes()->ID;
$tarifa_grupo = (string)$XML->VehResRQCore->RateQualifier->attributes()->RateAuthorizationCode;
$web_flota_acriss = (string)$XML->VehResRQCore->VehPref->VehClass;
$web_flota_similar = (string)$XML->VehResRQCore->VehPref->VehType;
$loc_pickup = (int)$XML->VehAvailRQCore->VehRentalCore->PickUpLocation->attributes()->LocationCode;
$loc_dropoff = (int)$XML->VehAvailRQCore->VehRentalCore->ReturnLocation->attributes()->LocationCode;
$loc_pickup_text = $ctTextLoc["$locpu_text"];
$loc_dropoff_text = $ctTextLoc["$locdo_text"];
$pickup_time_hr = date("H", strtotime($DateIn));
$pickup_time_min = date('i', strtotime($DateIn));
$dropoff_time_hr = date("H", strtotime($DateOut));
$dropoff_time_min = date('i', strtotime($DateOut));
$costo_dias = (int)$XML->VehResRQCore->VehicleCharges->Vehiclecharge->Calculation->attributes()->Unitcharge;
$costo_semana = 0;
$costo_horas = 0;
$total_dias = (int)$XML->VehResRQCore->VehicleCharges->Vehiclecharge->Calculation->attributes()->Quantity;
$total_semanas = 0;
$total_horas = 0;
$total_renta = (int)$XML->VehResRQCore->VehicleCharges->Vehiclecharge->Calculation->attributes()->total;
$total_extras = 0;
$imp_iva = (int)$XML->VehResRQCore->VehicleCharges->Vehiclecharge->TaxAmounts->TaxAmount->attributes()->Total;
$imp_aepto = (float)$XML->VehResRQCore->Fees->Fee->attributes()->Amount;
$total_total = "";
$moneda = (string)$XML->VehResRQCore->VehicleCharge->attributes()->CurrencyCode;
$extras = serialize($XML->VehresRQCore->TPA_Extensions->SOE_ExtrasRequest);
$st = "";
$flight_number = (string)$XML->SpecificFlightInfoType->FlightNumber;
$flight_airline = (string)$XML->SpecificFlightInfoType->Airline;
$comments = (string)$XML->VehresRQCore->TPA_Extensions->SOE_Comments->Comment->text;
foreach ($XML->VehresRQCore->TPA_Extensions->SOE_ExtrasRequest->attributes()->Amount as $item => $value){
$total_extras += $value;
}
$rInsert = new Reservacion;
$cInsert = new ReservacionCliente;
$cInsert->salutation = (string)$salutation;
$cInsert->nombre = (string)$nombre;
$cInsert->apellidos = (string)$apellidos;
$cInsert->email = (string)$email;
$cInsert->telefono = (string)$telefono;
$cInsert->celular = (string)$celular;
$cInsert->ciudad = (string)$ciudad;
$cInsert->pais = (string)$pais;
$cInsert->estado = (string)$estado;
$cInsert->save();
$ClienteID = $cInsert->cliente_id;
/*if ($r["total_horas"] > 0) {
$horas = (int) ($r["total_horas"] / $r["costo_horas"]);
} else {
$horas = 0;
}*/
$rInsert->referencia = (string)$referencia;
$rInsert->tarifa_grupo = $tarifa_grupo;
$rInsert->web_flota_acriss = (string) $web_flota_acriss;
$rInsert->web_flota_similar = $web_flota_similar;
$rInsert->web_sitio_id = 5;
$rInsert->prefijo = "RCC";
$rInsert->code = self::getNextId('code','web_reservacion',$condicion = array('prefijo'),$parametro = array('RCC') );
$rInsert->web_cliente_id = $ClienteID;
$rInsert->fecha = date("Y-m-d H:i:s");
$rInsert->pickup = $datePickup;
$rInsert->dropoff = $dateDropoff;
$rInsert->loc_pickup = $ctLocations[(string) $loc_pickup];
$rInsert->loc_dropoff = $ctLocations[(string) $loc_dropoff];
$rInsert->loc_pickup_text = $loc_pickup_text;
$rInsert->loc_dropoff_text = $loc_dropoff_text;
$rInsert->pickup_time_hr = $pickup_time_hr;
$rInsert->dropoff_time_hr = $dropoff_time_hr;
$rInsert->pickup_time_min = $pickup_time_min;
$rInsert->dropoff_time_min = $dropoff_time_min;
$rInsert->costo_dias = $costo_dias;
$rInsert->costo_semana = $costo_semana;
$rInsert->costo_horas = $costo_horas;
$rInsert->total_dias = (int)$total_dias;
$rInsert->total_semanas = (int) $total_semanas;
$rInsert->total_horas = (int) $total_horas;
$rInsert->total_renta = $total_renta;
$rInsert->total_extras = $total_extras;
$rInsert->iva = $imp_iva;
$rInsert->impuesto_aeropuerto = $imp_aepto;
$rInsert->extras = serialize($extras);
$rInsert->total = $total_total;
$rInsert->moneda = $moneda;
$rInsert->estatus = $ctEstatus[$st];
$rInsert->flight_number = $flight_number;
$rInsert->flight_airline = $flight_airline;
$rInsert->dominio = "Rental Cars";
$rInsert->agente_callcenter = 0;
$rInsert->comments = $comments;
if((string)$XML->VehResRQCore->VehicleCharges->attributes()->Purpose == '022.VCP'){
$rInsert->pagada = 1;
$rInsert->pago_fecha = date("Y-m-d H:i:s");
$rInsert->pago_detalle = $total_renta;
$rInsert->pago_observacion = 'Prepago de la renta, pendiente los adicionales';
}
if (!$rInsert->save()) {
$Results['Success'] = 'false';
$Results['VehResRSCore']['#attributes'] = array(
'ReservationStatus' => 'Not Committed'
);
} else {
$Results['Success'] = 'true';
$Results['VehResRSCore']['#attributes'] = array(
'ReservationStatus' => 'Committed'
);
$Results['VehResRSCore']['VehReservation']['VehSegmentCore']['ConfID']['#attributes'] = array(
'Type' => '014.UIT',
'ID' => 'RCC-' . $rInsert->code
);
}
$xml = Array2XML::createXML('OTA_VehResRS', $Results);
echo str_replace("\n", "", (trim($xml->saveXML())));
}
Is so weird because with another XML script works pretty well exe:
`<OTA_VehLocSearchRQ Version="1.00">
<POS>
<Source>`enter code here`
<RequestorID ID="22"></RequestorID>
</Source>
</POS>
</OTA_VehLocSearchRQ>`
To the method:
public function OTA_VehLocSearchRQ($XML)
{
$Results = array();
$Results['#attributes'] = array(
'Version' => '1.00',
'TimeStamp' => date('c')
);
if ($XML->POS->Source->RequestorID->attributes()->ID == 22) { // Sistema 22 = Rental Cars
$XML->POS->Source->RequestorID->attributes()->ID = 16; //Proveedor 16 = Rental Cars
}
if (isset($XML->VehLocSearchCriterion)) {
$Results["Success"] = true;
$Results["VehMatchedLocs"] = array();
$Locaciones = Yii::app()->db->createCommand()
->select('*, c.Name as Pais, c.Code2 as Country2L')
->from('cr_locaciones')
->join("Country c", "c.Code = locacion_pais")
->join("City", "ID = locacion_ciudad")
->where("locacion_proveedor = :proveedor AND locacion_id = :codigo", array(":proveedor" => (string)$XML->POS->Source->RequestorID->attributes()->ID, ":codigo" => $XML->VehLocSearchCriterion->RefPoint))
->queryAll();
} else {
$Results["Success"] = true;
$Results["VehMatchedLocs"] = array();
$Locaciones = Yii::app()->db->createCommand()
->select('*, c.Name as Pais, c.Code2 as Country2L')
->from('cr_locaciones')
->join("Country c", "c.Code = locacion_pais")
->join("City", "ID = locacion_ciudad")
->where("locacion_proveedor = :proveedor", array(":proveedor" => $XML->POS->Source->RequestorID->attributes()->ID))
->queryAll();
}
if (sizeof($Locaciones) > 0) {
$Results["VehMatchedLocs"]["VehMatchedLoc"] = array();
foreach ($Locaciones as $l) {
$lInfo = array(
"LocationDetail" => array(
"#attributes" => array(
"Code" => $l["locacion_id"],
"Name" => $l["locacion_nombre_en"],
"AtAirport" => (($l["locacion_tipo"] == 2) ? true : false),
"CodeContext" => "PickupLocation",
),
"Address" => array(
"AddressLine" => utf8_encode($l["locacion_direccion_linea_1"]),
"CityName" => utf8_encode($l["Name"]),
"PostalCode" => $l["locacion_cp"],
"CountryName" => array(
"#attributes" => array("Code" => $l["Country2L"]),
"#value" => $l["Pais"],
),
),
"Telephone" => array(
"#attributes" => array(
"PhoneNumber" => $l["locacion_telefono"],
"FormattedInd" => false,
),
),
)
);
array_push($Results["VehMatchedLocs"]["VehMatchedLoc"], $lInfo);
}
} else {
$Results["Success"] = false;
}
$xml = Array2XML::createXML('OTA_VehLocSearchRS', $Results);
echo str_replace("\n", "", (trim($xml->saveXML())));
}
Someone can give tips, I have researched and I could not find anything.
A million thanks.
I found the mistake, the problem was the "foreach" I was not iterating the array pretty well.
foreach ($XML->VehResRQCore->Customer->Primary->Telephone as $Telephone) {
switch((string) $Telephone['PhoneTechType']) { // Obtener los atributos como índices del elemento
case '001.PTT':
$telefono = $Telephone['PhoneNumber'];
break;
case '005.PTT':
$celular = $Telephone['PhoneNumber'];
break;
}
}
To serialize the extras:
foreach ($XML->xpath('//Extra') as $Extras) {
array_push( $extras,(string)$Extras['Code'],(string)$Extras['Amount'],(string)$Extras['observations']);
}
Is the first time I work with XML... anyway, I got it!
I answer my question if is helpful to another one!

Creating default object from empty value ( stdClass? )

The script run good, but only when I fetching out the groups of the user, it's says:
SteamUser.php (132): Creating default object from empty value
function getProfileData() {
//Set Base URL for the query:
if(empty($this->vanityURL)) {
$base = "http://steamcommunity.com/profiles/{$this->userID}/?xml=1";
} else {
$base = "http://steamcommunity.com/id/{$this->vanityURL}/?xml=1";
}
try {
$content = SteamUtility::fetchURL($base);
if ($content) {
$parsedData = new SimpleXMLElement($content);
} else {
return null;
}
} catch (Exception $e) {
//echo "Whoops! Something went wrong!\n\nException Info:\n" . $e . "\n\n";
return null;
}
if(!empty($parsedData)) {
$this->steamID64 = (string)$parsedData->steamID64;
$this->steamID = (string)$parsedData->steamID;
$this->stateMessage = (string)$parsedData->stateMessage;
$this->visibilityState = (int)$parsedData->visibilityState;
$this->privacyState = (string)$parsedData->privacyState;
$this->avatarIcon = (string)$parsedData->avatarIcon;
$this->avatarMedium = (string)$parsedData->avatarMedium;
$this->avatarFull = (string)$parsedData->avatarFull;
$this->vacBanned = (int)$parsedData->vacBanned;
$this->tradeBanState = (string)$parsedData->tradeBanState;
$this->isLimitedAccount = (string)$parsedData->isLimitedAccount;
$this->onlineState = (string)$parsedData->onlineState;
$this->inGameServerIP = (string)$parsedData->inGameServerIP;
//If their account is public, get that info:
if($this->privacyState == "public") {
$this->customURL = (string)$parsedData->customURL;
$this->memberSince = (string)$parsedData->memberSince;
$this->steamRating = (float)$parsedData->steamRating;
$this->hoursPlayed2Wk = (float)$parsedData->hoursPlayed2Wk;
$this->headline = (string)$parsedData->headline;
$this->location = (string)$parsedData->location;
$this->realname = (string)$parsedData->realname;
$this->summary = (string)$parsedData->summary;
}
//If they're in a game, grab that info:
if($this->onlineState == "in-game") {
$this->inGameInfo = array();
$this->inGameInfo["gameName"] = (string)$parsedData->inGameInfo->gameName;
$this->inGameInfo["gameLink"] = (string)$parsedData->inGameInfo->gameLink;
$this->inGameInfo["gameIcon"] = (string)$parsedData->inGameInfo->gameIcon;
$this->inGameInfo["gameLogo"] = (string)$parsedData->inGameInfo->gameLogo;
$this->inGameInfo["gameLogoSmall"] = (string)$parsedData->inGameInfo->gameLogoSmall;
}
//Any weblinks listed in their profile:
if(!empty($parsedData->weblinks)) {
$this->weblinks = array();
$i = 0;
foreach ($parsedData->weblinks->weblink as $weblink) {
$this->weblinks[$i]->title = (string)$weblink->title;
$this->weblinks[$i]->link = (string)$weblink->link;
$i++;
}
}
if(!empty($parsedData->groups)) {
$this->groups = array();
$i = 0;
foreach ($parsedData->groups->group as $group) {
$this->groups[$i]->groupID64 = (string)$group->groupID64; // row 132 in script
$this->groups[$i]->groupName = (string)$group->groupName;
$this->groups[$i]->groupURL = (string)$group->groupURL;
$this->groups[$i]->headline = (string)$group->headline;
$this->groups[$i]->summary = (string)$group->summary;
$this->groups[$i]->avatarIcon = (string)$group->avatarIcon;
$this->groups[$i]->avatarMedium = (string)$group->avatarMedium;
$this->groups[$i]->avatarFull = (string)$group->avatarFull;
$this->groups[$i]->memberCount = (string)$group->memberCount;
$this->groups[$i]->membersInChat = (string)$group->membersInChat;
$this->groups[$i]->membersInGame = (string)$group->membersInGame;
$this->groups[$i]->membersOnline = (string)$group->membersOnline;
$i++;
}
}
}
}
.
.
.
I already tried to using associative arrays, but didn't work; maybe with doing it all new. -_-
So, I can't set error_reporting(0) or ini_set at all.
I also used new stdClass() as a try. But I didn't get this running too.
You create an array.
$this->groups = array();
But in this array you donot create any object. You just use this array's elements (thoes are not initialized) as objects. You should add this line before your 132. row.
$this->groups[$i] = new Group();
Or something similar.
If you do not have Group class you should try
$this->groups[$i] = new stdClass();

Evernote API findNotesMetadata php

I am trying to retrieve a list of notes from the Evernote API, and the script I am using returns a screen that says "whoops something went wrong"
<?php
$token = 'S=s1:U=904d8:E=152a2ea0df7:C=14b4b38e1d0:P=1cd:A=en-devtoken:V=2:H=c28ff07ca3ee987b8c916cfc0c536e99';
$sandbox = true;
$client = new \Evernote\Client($token, $sandbox);
$notebookGuid = "c1977c63-ffc7-4876-a071-67fd6ea9fd4c";
$filter = new NoteFilter();
// $filter->notebookGuid = $notebookGuid;
$offset = 0;
$spec = new NotesMetadataResultSpec();
$spec->includeTitle = true;
$spec->includeContentLength = true;
$spec->includeCreated = true;
$spec->includeUpdated = true;
//$spec->includeDeleted = true;
$spec->includeUpdateSequenceNum = true;
$spec->includeNotebookGuid = true;
$spec->includeTagGuids = true;
$spec->includeAttributes = true;
$spec->includeLargestResourceMime = true;
$spec->includeLargestResourceSize = true;
// $resultSpec->includeTitle = true;
$notes = $client->findNotesMetadata($token, $filter, 0, 10,$spec);
First, I think you should comment out the line where you assign the notebookGuid to filter.
Second, findNotesMetadata is a method of a NoteStore object.
So, the last lines should look like that:
$noteStore = $client->getNoteStore();
$notes = $noteStore->findNotesMetadata($token, $filter, 0, 10, $spec);

Using ZeroMQ (PHP-ZMQ) for loop operations

I'm trying to use heavy resource content loop operation with ZeroMQ (PHP-ZMQ) via tcp protocol.
I've got below code so far:
class SJB_Miscellaneous_SendNotifications extends SJB_Function
{
public function execute()
{
try{
set_time_limit(0);
$i18n = SJB_I18N::getInstance();
$lang = $i18n->getLanguageData($i18n->getCurrentLanguage());
$current_date = strftime($lang['date_format'], time());
// Send Search Notifications
$saved_searches = SJB_SavedSearches::getAutoNotifySavedSearches();
// echo "<pre>"; print_r($saved_searches); echo "</pre>"; exit;
$listing = new SJB_Listing();
$notified_saved_searches_sid = array();
$notificationsLimit = (int) SJB_Settings::getSettingByName('num_of_listings_sent_in_email_alerts');
/* ZeroMQ implementation */
$queue = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ, "MySock1");
$queue->connect("tcp://127.0.0.1:5555");
/* Assign socket 1 to the queue, send and receive */
$time = time();
$queue->send(json_encode($saved_searches));
// echo $queue->recv();
// exit;
$count = 1;
// array_shift($saved_searches);
$server = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REP);
$server->bind("tcp://127.0.0.1:5555");
$msg = $server->recv();
$saved_searches = json_decode($msg, true);
// echo "<pre>"; var_dump($saved_searches); echo "</pre>";
// exit;
foreach ($saved_searches as $saved_search) {
$searcher = new SJB_ListingSearcher();
$listing->addActivationDateProperty();
$search_data = unserialize($saved_search['data']);
$search_data['active']['equal'] = 1;
$datearr = explode('-', $saved_search['last_send']);
$saved_search['last_send'] = strftime($lang['date_format'], mktime(0, 0, 0, $datearr[1], $datearr[2], $datearr[0]));
$search_data['activation_date']['not_less'] = $saved_search['last_send'];
$search_data['activation_date']['not_more'] = $current_date;
$listing_type_sid = 0;
if ($search_data['listing_type']['equal']) {
$listing_type_id = $search_data['listing_type']['equal'];
$listing_type_sid = SJB_ListingTypeManager::getListingTypeSIDByID($listing_type_id);
if (SJB_ListingTypeManager::getWaitApproveSettingByListingType($listing_type_sid))
$search_data['status']['equal'] = 'approved';
}
// echo "<pre>"; echo $saved_search['user_sid']; print_r($listing_type_id); echo "</pre>"; exit;
$id_alias_info = $listing->addIDProperty();
$username_alias_info = $listing->addUsernameProperty();
$listing_type_id_info = $listing->addListingTypeIDProperty();
$aliases = new SJB_PropertyAliases();
$aliases->addAlias($id_alias_info);
$aliases->addAlias($username_alias_info);
$aliases->addAlias($listing_type_id_info);
$search_data['access_type'] = array(
'accessible' => $saved_search['user_sid'],
);
$criteria = SJB_SearchFormBuilder::extractCriteriaFromRequestData($search_data, $listing);
$searcher->found_object_sids = array();
$searcher->setLimit($notificationsLimit);
$sorting_fields = array('CityRegion' => 'ASC');
$found_listings_ids = $searcher->getObjectsSIDsByCriteria($criteria, $aliases, $sorting_fields);
// echo "<pre>"; var_dump($found_listings_ids); echo "</pre>";
if (count($found_listings_ids)) {
$saved_search['activation_date'] = $saved_search['last_send'];
if (SJB_Notifications::sendUserNewListingsFoundLetter($found_listings_ids, $saved_search['user_sid'], $saved_search, $listing_type_sid)) {
SJB_Statistics::addStatistics('sentAlert', $listing_type_sid, $saved_search['sid']);
SJB_DB::query('UPDATE `saved_searches` SET `last_send` = CURDATE() WHERE `sid` = ?n', $saved_search['sid']);
}
$notified_saved_searches_sid[] = $saved_search['sid'];
}
echo nl2br($count."\n");
$count++;
}
// To be entered from task_scheduler.php
$expired_contracts_id = null; $expired_listings_id = null;
$template_processor = SJB_System::getTemplateProcessor();
$template_processor->assign('expired_listings_id', null);
$template_processor->assign('deactivated_listings_id', null);
$template_processor->assign('expired_contracts_id', null);
$template_processor->assign('notified_saved_searches_id', $notified_saved_searches_sid);
$scheduler_log = $template_processor->fetch('task_scheduler_log.tpl');
if ($log_file = #fopen('task_scheduler.log', 'a+')) {
fwrite($log_file, $scheduler_log);
fclose($log_file);
}
SJB_DB::query('INSERT INTO `task_scheduler_log`
(`last_executed_date`, `notifieds_sent`, `expired_listings`, `expired_contracts`, `log_text`)
VALUES ( NOW(), ?n, ?n, ?n, ?s)',
count($notified_saved_searches_sid), count($expired_listings_id), count($expired_contracts_id), $scheduler_log);
} catch(Exception $e){
echo $e->getMessage();
}
}
} // END class SJB_Miscellaneous_SendNotifications extends SJB_Function
Is there a good way to utilise ZeroMQ for this type of operation where I want to free loop operations especially when it reaches $saved_searches foreach loop?

Categories