Jeff Berlin
Jeff Berlin

Reputation: 600

Using PHP simplexml parsing

I am trying to parse some XML from a link, but to update the link to pull the correct item information, comes from the correct $product_id.

The goal is to click a button (a $product_id number is set to each button) and then it will show the product information that I parse onto that same page or a different page into a table (think of an add-to-cart button and shopping cart display).

I have the following defined globally, but I am not sure if the $product_id variable is being used properly for the link:

$xml = simplexml_load_file("https://secure.bmtmicro.com/cart?CID=2/WP&PRODUCTID=' . $product_id . '");

I've been trying to call $xml inside of a function that should output the information, but it's not working, so I just want to start my troubleshooting from the beginning. Is simplexml_load_file() even the best way to pull from a URL and if so, am I even setting up the variable properly? (I am fairly new to PHP). Thanks in advance!

The function that I'm using to try and show the product information is:

function print_cart($args = array()) { 
  #some other code that doesn't involve the $xml

    if ($_SESSION['simpleCart'] && is_array($_SESSION['simpleCart'])){
      $output .= '
        <tr class="cart_item_row">
        <th class="cart_item_name_th">' . (__("Product Name")) . '</th><th class"bmt_cart_qty_th">' . (__("quantity")) . '</th><th class="cart_price_th">' . (__("Price")) . '</th><th></th>
        </tr>';

        foreach ($xml->children() as $product) {
            echo $product->productname;
        }

    $output .= "</table></div>";
    $output = apply_filters('after_cart_output', $output);
    return $output;
}

This is the original XML content (using random product id and its info):

<shoppingcart>
  <producttable>
    <row number="0">
      <productid>22804</productid>
      <productname>XFree86 CD</productname>
      <quantity>1</quantity>
      <productprice>$15.00</productprice>
      <discount>$0.00</discount>
      <rowtotal>$15.00</rowtotal>
    </row>
    <row number="1">
      <productid>193</productid>
      <productname>Testproduct - Remote Key Generator</productname>
      <quantity>1</quantity>
      <productprice>$0.99</productprice>
      <discount>$0.50</discount>
      <rowtotal>$0.49</rowtotal>
    </row>
  </producttable>
</shoppingcart>

Upvotes: 0

Views: 291

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57131

Your foreach is probably picking up the wrong elements. When you use ->children(), this is every child element of the start point. This isn't always what you want. What this code does is loop over the producttable elements and then the row elements within that (which is where the ->producttable->row comes from)

foreach ( $xml->producttable->row as $product ) {
    echo $product->productname.PHP_EOL;
}

With your sample data, this gives...

XFree86 CD
Testproduct - Remote Key Generator

Upvotes: 1

Related Questions