首页 > 解决方案 > 更新用于在 PHP 中解析 XML 的 URL

问题描述

我试图弄清楚如何更新我用来解析 XML 的 URL(使用simplexml_load_file())。

当用户添加他们的简码时,有button一个$productid由用户分配给它的[show_cart_button productid=#]

//code for the button input that gets called    

function print_add_cart_button($productid, $atts = array()) {
   //some other form code for the button

   $replacement .= '<input type="hidden" name"cart_product" value"' . $productid . '"/>';
  return $replacement;
}

这是function我用来显示和调用产品信息的:

function show_shopping_cart_handler($atts) {
   if (isset($_POST['cart_product'])) {
      $id = "&PRODUCTID=" . $_POST['cart_product'];
    // uses the input name from the button
   }

   $url = "https://secure.bmtmicro.com/cart?CID=2/WP" . $id;
   
   $xml = simplexml_load_file($url) or die("error.");

   foreach ($xml->producttable->row as $product) {
      $output .= '<span>' . $product->productname . '</span>';
   }

   return $output;
}

URL 正常工作的方式是在 URL&PRODUCTID=(product#)的末尾添加一个。例如,如果您单击两个不同的按钮,则 URL 应如下所示:(https://secure.bmtmicro.com/cart?CID=2/WP&PRODUCTID=1&PRODUCTID=2显然 1 和 2 需要显示按钮$productid编号)。

正如您应该能够从我上面的代码中看到的那样,每次button单击 a 时,它都会重写 URL 并显示该产品,而不是在列表中添加新产品。我尝试将其设置simplexml_load_file()为 a foreach(),但单击按钮时不会显示任何产品。有谁知道我可以让该 URL 更新/正常工作的方法?

标签: phpwordpress

解决方案


每次

 if (isset($_POST['cart_product'])) {
      $id = "&PRODUCTID=" . $_POST['cart_product'];
    // uses the input name from the button
   }

被调用,它覆盖$id。您需要获取 url 的任何现有值。

您必须获取所有当前值 ($_GET['cart_productions']),将它们放入数组中,获取新帖子,将其添加到数组中,然后使用 http_build_query() 将它们全部添加到 url .


推荐阅读