首页 > 解决方案 > 使用 curl 检索 api 数据

问题描述

我正在写 woocommerce rest api。当我使用 curl 连接到 single_product_connect.php 时,出现“snytax 错误”错误。我该如何解决这个问题。我的目标是编写这段代码。选择我的 Woocommerce 产品列表中的任何产品并查看该产品的详细信息。表格代码;

<form action="single_product.php" name="update" method="get">
<td><input type="submit" name="edit"id="edit" value="<?= $row['id']; ?>"/></td> 
</form>

单产品.php;

<?php

$ch = curl_init();


$url = "http://localhost/api-woocommerce/single_product_connect.php?<queryParam>=<product_id>";
curl_setopt($ch, CURLOPT_URL, $url);


curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);


$output = curl_exec($ch);


curl_close($ch);

$data = json_decode($output, true);

if (json_last_error() !== JSON_ERROR_NONE) {
echo json_last_error_msg();
exit();
}

foreach ($data as $row) {
    $row['name'];
}
?>

single_product_connect.php

<?php
require __DIR__ . '/vendor/autoload.php';

use Automattic\WooCommerce\Client;

$woocommerce = new Client(
'https://blog.test.com',
'ck_bb7cb132da9dfac541570',
'cs_327a1926654e4e20610',
[
    'wp_api' => true,
    'version' => 'wc/v3',
    'query_string_auth' => true // Force Basic Authentication as query string true and using under 
HTTPS
]
);
?>
<?php $product_id = $_GET['edit'];?>
<?php echo json_encode($woocommerce->get("products/{$product_id}",$data)); ?>

错误画面;

Syntax error

标签: phpcurlwoocommerce

解决方案


您收到的错误很可能与single_product_connect.php文件有关:

Parse error: syntax error, unexpected 'HTTPS' (T_STRING), expecting ']' in your code on line 14

所有你需要的是:

  • 在后面加一个逗号'query_string_auth' => true (这样就可以了'query_string_auth' => true,
  • HTTPS如果不存在则删除文本(请记住,以这种方式编写的它被视为常量,如果要将其用作字符串,则必须使用引号)

为了超越您的问题,我建议您还阅读以下答案:


推荐阅读