我一直在使用这个resource作为参考,将基于Joomla 3的CLI脚本转换为基于Joomla 4/5的API脚本。该脚本从外部API检索新闻帖子,并将其作为单独的文章添加到Joomla。
我有$process
函数工作。它成功地连接到外部API,并在使用print_r
函数时在浏览器中输出数据数组。我在下面包含了完整的$process
函数。
$process = function (string $givenHttpVerb, string $endPoint, string $dataString, array $headers, int $timeOut, $transport) {
curl_setopt_array($transport, [
CURLOPT_URL => $endPoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => 'utf-8',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => $timeOut,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2TLS,
CURLOPT_CUSTOMREQUEST => $givenHttpVerb,
CURLOPT_POSTFIELDS => $dataString,
CURLOPT_HTTPHEADER => $headers,
]
);
$response = curl_exec($transport);
if (empty($response)) {
throw new RuntimeException( 'Empty output', 422 );
}
return $response;
};
字符串
使用$dataSourceResponse = $process($dataSourceHttpVerb, $dataSourceUrl, $dataSourceDataString, $dataSourceHeaders, $dataSourceTimeout, $dataSourceTransport);
调用$process
函数
我有一个$generator
函数,它接受$dataSourceResponse
匿名函数和$apiUrl
,这是基于Joomla的网站。$apiUrl
是 * upgrade.domain.com/api/index.php/v1*。完整的$generator
函数包含在下面。
$generator = function (string $dataSourceResponse): Generator {
if (empty($dataSourceResponse)) {
yield new RuntimeException( 'DTN API response must not be empty', 422 );
}
$resource = json_decode($dataSourceResponse);
if ($resource === false) {
yield new RuntimeException( 'Could not read response from source DTN API', 500 );
}
try {
foreach ($resource as $article) {
$data = [
'id' => 0,
'catid' => 13,
'title' => $article->title,
'articletext' => $article->content,
'introtext' => $article->storySummary,
'fulltext' => $article->content,
'note' => $article->topic,
'state' => 1,
'access' => 1,
'created_by' => 386,
'created_by_alias' => 'DTN News',
'language' => '*',
];
}
$dataString = json_encode($data);
} finally {
echo 'Done processing data' . PHP_EOL;
}
};
型
使用$postData = $generator($dataSourceResponse, $apiUrl);
调用$generator
函数
当我使用print_r
作为$postData
变量时,浏览器中显示以下内容:Generator Object() Done processing data
。
在我看来,从外部API检索的数据没有成功地与$generator
函数共享,该函数用于通过API将新闻帖子项目插入Joomla文章。
我在下面提供了完整的PHP脚本供参考。
declare(strict_types=1);
ini_set('error_reporting', E_ALL & ~E_DEPRECATED);
$dataSourceUrl = 'https://api.dtn.com/publishing/news/articles?categoryId=1%2C2%2C3%2C4%2C5%2C6%2C16%2C17&limit=10&maxAge=15&apikey=redacted';
$apiUrl = 'https://upgrade.domain.com/api/index.php/v1';
$token = redacted;
$timeOut = 60;
$generator = function (string $dataSourceResponse): Generator {
if (empty($dataSourceResponse)) {
yield new RuntimeException( 'DTN API response must not be empty', 422 );
}
$resource = json_decode($dataSourceResponse);
if ($resource === false) {
yield new RuntimeException( 'Could not read response from source DTN API', 500 );
}
try {
foreach ($resource as $article) {
$data = [
'id' => 0,
'catid' => 13,
'title' => $article->title,
'articletext' => $article->content,
'introtext' => $article->storySummary,
'fulltext' => $article->content,
'note' => $article->topic,
'state' => 1,
'access' => 1,
'created_by' => 386,
'created_by_alias' => 'DTN News',
'language' => '*',
];
}
$dataString = json_encode($data);
} finally {
echo 'Done processing data' . PHP_EOL;
}
};
$process = function (string $givenHttpVerb, string $endPoint, string $dataString, array $headers, int $timeOut, $transport) {
curl_setopt_array($transport, [
CURLOPT_URL => $endPoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => 'utf-8',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => $timeOut,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2TLS,
CURLOPT_CUSTOMREQUEST => $givenHttpVerb,
CURLOPT_POSTFIELDS => $dataString,
CURLOPT_HTTPHEADER => $headers,
]
);
$response = curl_exec($transport);
if (empty($response)) {
throw new RuntimeException( 'Empty output', 422 );
}
return $response;
};
$dataSourceHttpVerb = 'GET';
$dataSourceDataString = '';
$dataSourceHeaders = [
'Accept: application/json',
'Accept-Encoding: deflate, gzip, br',
'Content-Type: application/json',
'Connection: keep-alive',
];
$dataSourceTimeout = 60;
$dataSourceTransport = curl_init();
try {
$dataSourceResponse = $process($dataSourceHttpVerb, $dataSourceUrl, $dataSourceDataString, $dataSourceHeaders, $dataSourceTimeout, $dataSourceTransport);
$postData = $generator($dataSourceResponse, $apiUrl);
foreach ($postData as $dataString) {
if (!is_string($dataString)) {
continue;
}
$curl = curl_init();
try {
$headers = [
'Accept: application/vnd.api+json',
'Content-Type: application/json',
'Content-length: ' . mb_strlen($dataString),
sprintf('X-Joomla-Token: %s', trim($token)),
];
$output = $process('POST', $apiUrl, $dataString, $headers, $timeOut, $curl);
} catch (Throwable $e) {
echo $e->getMessage() . PHP_EOL;
continue;
} finally {
curl_close($curl);
}
}
} catch (Throwable $e) {
echo $e->getMessage() . PHP_EOL;
} finally {
curl_close($dataSourceTransport);
}
型
下面是基于CLI的脚本的PHP foreach loop
的运行情况,我尝试将其改编为参考。
foreach ($articles as $article) {
$articleData = [
'id' => 0,
'catid' => 13,
'title' => $article->title,
'introtext' => $article->storySummary,
'fulltext' => $article->content,
'note' => $article->topic,
'state' => 1,
'access' => 1,
'created_by' => 386,
'created_by_alias' => 'DTN News',
'language' => '*',
];
if (!$articleModel->save($articleData)) {
throw new Exception($articleModel->getError());
}
}
型
更新
在数据数组上使用var_dump(json_encode($data)); die();
的输出:
{
"id": 0,
"catid": 13,
"title": "DTN Midday Livestock Comments",
"articletext": "Firm gains redeveloped early Wednesday morning in live cattle and feeder cattle trade. This support has helped to spark some underlying follow-through buying in nearby and deferred contracts, supporting triple-digit gains through the morning. Hog futures are lightly traded but holding narrow losses at midday based on softness in pork fundamentals.<\\/span>",
"introtext": "Firm gains redeveloped early Wednesday morning in live cattle and feeder cattle trade. This support has helped to spark some underlying follow-through buying in nearby and deferred contracts, supporting triple-digit gains through the morning. Hog futures are lightly traded but holding narrow losses at midday based on softness in pork fundamentals.<\\/span>",
"fulltext": "Firm gains redeveloped early Wednesday morning in live cattle and feeder cattle trade. This support has helped to spark some underlying follow-through buying in nearby and deferred contracts, supporting triple-digit gains through the morning. Hog futures are lightly traded but holding narrow losses at midday based on softness in pork fundamentals.<\\/span>",
"note": "DTN\\/Ag\\/Markets",
"state": 1,
"access": 1,
"created_by": 386,
"created_by_alias": "DTN News",
"language": "*"
}
型
1条答案
按热度按时间utugiqy61#
我已经通过重构我的代码和实现一些缺失的功能,从我使用的resource作为这个脚本的基础解决了我的问题。我强调了重构的代码和新实现的代码,以及完整的脚本作为参考。
通过将
yield (json_encode($data));
移动到循环内部来重构$data foreach loop
。我还添加了字符串操作函数来清理一些导入的文本内容。字符串
我从资源中包含了这个匿名函数来处理外部和Joomla端点。这对于解决我在重构代码时遇到的
404 Resource not found
错误至关重要。型
我从
$postData
匿名函数中删除了$apiUrl
变量,因为它是不必要的。型
最后一个
try > catch > finally
中的第一个foreach loop
被重构,以检查API的PATCH
或POST
,并处理新包含的$endPoint
匿名函数。型
第二个
foreach loop
被添加来处理错误和检查Joomla文章的重复别名。型
完整脚本
型