I am trying to write a function to import data from an external XML feed.
This is the XML feed - https://www.benchmarkintl.com/feed/business_sale_report_businessfeed.xml
Below is the function which will match the application database field with the XML feed field and will import the feed content into the database.
public function getBenchmarkXmlFeed() {
$url= 'https://www.benchmarkintl.com/feed/business_sale_report_businessfeed.xml';
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$response = file_get_contents($url, false, stream_context_create($arrContextOptions));
$xmlString = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
$xml = simplexml_load_string($xmlString, "SimpleXMLElement", LIBXML_NOCDATA);
$count = 0;
foreach ( $xml->business as $business ) {
$businessObj = Businesses::where(["user_ref" => (string)$business->reference]);
if( !$businessObj ) {
$businessObj = new Businesses();
$businessObj->type = (string)$business->title;
if( isset($business->keyaspects) ) {
$businessObj->extra_description = strip_tags((string)$business->keyaspects);
}
$businessObj->country = "UK";
$businessObj->save();
$count++;
}
}
echo $count." new businesses has been send for approval";
}
this function works well
Problem
I want to add a condition. This function must only import the business where the country is UK. If there is a country that is not UK it must skip that content and proceed with the next one.
How to add that condition in this function
My Answer:
You can add a condition to check if the country is UK before importing the business data. Here's how you can modify your function to include this condition:
php
public function getBenchmarkXmlFeed() {
$url= 'https://www.benchmarkintl.com/feed/business_sale_report_businessfeed.xml';
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$response = file_get_contents($url, false, stream_context_create($arrContextOptions));
$xmlString = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
$xml = simplexml_load_string($xmlString, "SimpleXMLElement", LIBXML_NOCDATA);
$count = 0;
foreach ( $xml->business as $business ) {
if ((string)$business->country !== "UK") {
continue; // Skip this business if country is not UK
}
$businessObj = Businesses::where(["user_ref" => (string)$business->reference])->first();
if( !$businessObj ) {
$businessObj = new Businesses();
$businessObj->type = (string)$business->title;
if( isset($business->keyaspects) ) {
$businessObj->extra_description = strip_tags((string)$business->keyaspects);
}
$businessObj->country = "UK";
$businessObj->save();
$count++;
}
}
echo $count." new businesses have been sent for approval";
}
By adding the `if ((string)$business->country !== "UK")` condition before processing the business data, you can ensure that only businesses with the country set to "UK" will be imported into your database.
Rate this post
4 of 5 based on 9777 votesComments