How can I optimize a PHP script that fetches 1M+ MySQL rows for reporting without exhausting memory? [duplicate]

I’m working on a PHP web application that generates reports from a MySQL table with over 1 million rows.

What I’m trying to do:

  • Fetch a large dataset and process it to generate a downloadable report (CSV format).

  • Improve speed and reduce memory usage.

What I’ve tried:

  • Pagination: I tried using LIMIT and OFFSET in chunks of 10,000.

  • Indexing: The main table is indexed on user_id and created_at.

  • Redis: I cache commonly accessed parts of the result set.

  • Output buffering: Used ob_flush() and flush() to stream output.

What I expected:

  • Significant reduction in memory usage and generation time.

  • Avoid timeouts and memory exhaustion.

What actually happened:

  • Still facing high memory usage (Allowed memory size exhausted) when generating large reports.

  • Execution time exceeds 30 seconds in some cases

set_time_limit(0);
ini_set('memory_limit', '512M');

$offset = 0;
$limit = 10000;
$fp = fopen('php://output', 'w');

while (true) {
    $query = "SELECT * FROM reports_table ORDER BY created_at ASC LIMIT $limit OFFSET $offset";
    $results = mysqli_query($conn, $query);

    if (mysqli_num_rows($results) == 0) break;

    while ($row = mysqli_fetch_assoc($results)) {
        fputcsv($fp, $row);
    }

    $offset += $limit;
    ob_flush();
    flush();
}

Stripe Auto-Payment does not working properly

I am encountering an issue with Stripe’s auto-payment process.

I need to create Stripe subscriptions in the unpaid state, setting the first payment date in the future. I can successfully create the subscription and set the future date using the trial_end parameter.

However, when the time comes for Stripe to process the automatic payment, the payment doesn’t go through properly — instead, Stripe creates the invoice in a draft state. As a result, the invoice.payment_succeeded webhook also fails to trigger and send the request to our website.

Below is create subscription request parameter:

API: https://api.stripe.com/v1/subscriptions

Method: POST

Authorization / Header: I am sending it correctly

Request Parameter:

trial_end:1746253519
items[0][price]:`my plan value`
customer:`stripe customer id`
proration_behavior:always_invoice
collection_method:charge_automatically
default_payment_method:`default payment id`

Note:
The same process works correctly when I create a Stripe subscription with a paid status — in that case, the auto-payment runs successfully, and the webhook (invoice.payment_succeeded) properly sends the response to our website.

I also tried modifying the request by adding the billing_cycle_anchor parameter, but I’m still facing the same issue.

Can someone help me understand what might be wrong with the parameters in my subscription creation request?

Thank you.

ECDSA-signed JWT validation failures between .NET and PHP

Why does a ECDSA-signed JWT in .NET fail validation in PHP when using OpenSSL, even with matching keys and algorithms?

  • In .NET using System.Security.Cryptography and System.IdentityModel.Tokens.Jwt packages.
  • In PHP using OpenSSL extension and Firebase's JWT library.
  • Algo: ECDSA(ES256)
  • Public key format: PEM

My example .NET code to generate JWT:

// ECDSA-signed JWT

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using Microsoft.IdentityModel.Tokens;

var privateKey = ECDsa.Create(ECCurve.NamedCurves.nistP256); // ES256
var securityKey = new ECDsaSecurityKey(privateKey) { KeyId = "1" };
var credentials = new SigningCredentials(securityKey, "ES256");
var token = new JwtSecurityToken(
    issuer: "https://example.com",
    audience: "https://example.com",
    claims: new[] { new Claim("test", "value") },
    expires: DateTime.UtcNow.AddHours(1),
    signingCredentials: credentials
);
var jwt = new JwtSecurityTokenHandler().WriteToken(token);
Console.WriteLine("JWT (will fail in PHP): " + jwt);
Console.Read();

My example PHP code to consume JWT:

<?php

require 'vendor/autoload.php';

use FirebaseJWTJWT;
use FirebaseJWTKey;

$jwt = '<JWT STRING HERE>'; // From .NET
$publicKey = openssl_pkey_get_public('path/to/public_key.pem'); // PEM-formatted public key.
try
{
   $decoded = JWT::decode($jwt, new Key($publicKey, 'ES256'));
   print_r($decoded);
}
catch (Exception $e)
{
   echo 'Validation error: ' . $e->getMessage();
}

PHP output:

Validation error: OpenSSL error: error:1C800064:Provider routines::bad signature

My instructions to create EXTRA ECDSA PEM formatted public-key for JWT:

# Generate private-key.
openssl ecparam -name prime256v1 -genkey -noout -out ec-private-key.pem

# Extract public-key from private-key.
openssl ec -in ec-private-key.pem -pubout -out ec-public-key.pem

Output files:

  • ec-private-key.pem (private)
  • ec-public-key.pem (public, for JWT validation).

Any idea why this happens?

bimber theme is not activating even i have purchased code [closed]

I have bimber WordPress theme which i bought in 2019 I have a license code, even when i try to put the code it says error you can see in attach picture

enter image description here

error : Token Registration
When automatic registration fails, please unlock the theme using this token method. Click the following link to get your individual token and enter it below. Generate token

when i click generate token, it gives error 404 on this link https://api.bringthepixel.com/?action=register&theme=bimber&purchase_code=5b8dff06-e999-4021-8d75-1e828fa50a10&site_url=https%3A%2F%2Fpakistantopstories.com

as the website is no longer available any help on that

any one help on that so can i fix it manually by any way

Custom WordPress Customizer Control for Typography Presets renders blank section or fallback , despite correct class registration

Problem
I’m building a WordPress theme and want a Global → Typography → Font Presets control in the Customizer that shows a grid of clickable cards (each card previews a heading/body Google-Font pair). Instead of my custom card UI, the section is either blank or falls back to a basic <select> (or radio list) control. I’ve tried many variations of register_control_type(), direct instantiation, OPcache resets, and cleanup of duplicate classes, but no luck.

What I’ve Done
Autoloader in functions.php (recursively includes /inc/ files):

// in functions.php
$rii = new RecursiveIteratorIterator(
  new RecursiveDirectoryIterator( __DIR__ . '/inc' )
);
foreach ( $rii as $file ) {
  if ( ! $file->isDir() && $file->getExtension() === 'php' ) {
    require_once $file->getPathname();
  }
}

Bootstrap singleton in inc/class-zero-customizer.php:

<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class Zero_Customizer {
  private static $instance = null;

  public static function get_instance() {
    if ( null === self::$instance ) {
      self::$instance = new self();
      self::$instance->hooks();
    }
    return self::$instance;
  }

  private function hooks() {
    error_log( 'Zero: hooks() running' );
    add_action( 'customize_register',                [ $this, 'register_typography_control' ] );
    add_action( 'customize_controls_enqueue_scripts',[ $this, 'enqueue_control_assets' ] );
    add_action( 'customize_preview_init',            [ $this, 'enqueue_preview_assets' ] );
  }

  public function register_typography_control( $wp_customize ) {
    error_log( 'Zero: register_typography_control() fired' );
    require_once __DIR__ . '/customizer/controls/class-zero-control-typography.php';

    // Panel & section
    if ( ! $wp_customize->get_panel( 'zero_global_panel' ) ) {
      $wp_customize->add_panel( 'zero_global_panel', [
        'title'    => __( 'Global Settings', 'zero' ),
        'priority' => 10,
      ] );
    }
    $wp_customize->add_section( 'zero_typography_section', [
      'title'    => __( 'Typography', 'zero' ),
      'panel'    => 'zero_global_panel',
      'priority' => 10,
    ] );
    error_log( 'Zero: added section zero_typography_section' );

    // Presets & setting
    $presets = [
      'playfair-open-sans'         => esc_html__( 'Playfair Display / Open Sans', 'zero' ),
      /* …other 9 pairs… */
    ];
    $wp_customize->add_setting( 'zero_typography_preset', [
      'default'           => 'playfair-open-sans',
      'sanitize_callback' => function( $val ) use ( $presets ) {
        return isset( $presets[ $val ] ) ? $val : 'playfair-open-sans';
      },
      'transport'         => 'postMessage',
    ] );

    // Direct instantiation of custom control
    $wp_customize->add_control( new Zero_Control_Typography(
      $wp_customize,
      'zero_typography_preset',
      [
        'label'       => __( 'Font Presets', 'zero' ),
        'description' => __( 'Click a card to choose your Heading/Body pair.', 'zero' ),
        'section'     => 'zero_typography_section',
        'choices'     => $presets,
      ]
    ) );
    error_log( 'Zero: added custom-control for zero_typography_preset' );
  }

  public function enqueue_control_assets() {
    // Load panel CSS & JS
    wp_enqueue_style(
      'zero-customizer-controls',
      get_stylesheet_directory_uri() . '/assets/dist/css/main.min.css',
      [], filemtime( get_stylesheet_directory() . '/assets/dist/css/main.min.css' )
    );
    wp_enqueue_script(
      'zero-customizer-controls',
      get_stylesheet_directory_uri() . '/assets/dist/js/customizer.bundle.js',
      [ 'jquery','customize-controls' ],
      filemtime( get_stylesheet_directory() . '/assets/dist/js/customizer.bundle.js' ),
      true
    );
  }

  public function enqueue_preview_assets() {
    // Load iframe JS for live preview
    wp_enqueue_script(
      'zero-customizer-preview',
      get_stylesheet_directory_uri() . '/assets/dist/js/customizer.bundle.js',
      [ 'jquery','customize-preview' ],
      filemtime( get_stylesheet_directory() . '/assets/dist/js/customizer.bundle.js' ),
      true
    );
  }
}

add_action( 'after_setup_theme', [ 'Zero_Customizer', 'get_instance' ] );

Custom Control in inc/customizer/controls/class-zero-control-typography.php:

<?php
if ( ! class_exists( 'WP_Customize_Control' ) ) {
  return;
}
if ( ! class_exists( 'Zero_Control_Typography' ) ) {
  class Zero_Control_Typography extends WP_Customize_Control {
    public $type = 'typography';

    public function render_content() {
      error_log( 'Zero: Zero_Control_Typography::render_content()' );
      if ( empty( $this->choices ) ) {
        return;
      }

      echo '<span class="customize-control-title">' . esc_html( $this->label ) . '</span>';
      if ( $this->description ) {
        echo '<span class="description customize-control-description">'
             . esc_html( $this->description ) . '</span>';
      }

      echo '<ul>';
      foreach ( $this->choices as $slug => $name ) {
        $checked = checked( $this->value(), $slug, false );
        list( $h, $b ) = explode( '-', $slug, 2 );
        printf(
          '<li><label class="preset-card">'
          . '<input type="radio" data-customize-setting-link="%1$s" value="%2$s"%3$s />'
          . '<span class="preset-card__heading" style="font-family:'%4$s';">Heading</span>'
          . '<span class="preset-card__body"    style="font-family:'%5$s';">Body text</span>'
          . '</label></li>',
          esc_attr( $this->id ), esc_attr( $slug ), $checked,
          esc_attr( ucwords( str_replace('-', ' ', $h)) ),
          esc_attr( ucwords( str_replace('-', ' ', $b)) )
        );
      }
      echo '</ul>';
    }
  }
}

SCSS & JS

  • Imported into my normal assets/css/sass/main.scss and assets/js/customizer.js builds.
  • Enqueued in the panel via customize_controls_enqueue_scripts and preview via customize_preview_init.

Errors & Symptoms

  • Blank Typography section, despite register_typography_control() firing in the logs.

  • If I try array‐style or register_control_type(), it instead renders a plain <select> or radio list.

  • Encountered duplicate‐class “Cannot declare class Zero_Control_Typography” until I deleted old files.

  • Tried OPcache resets, restarting Docker, multiple include patterns—still no card UI.

Questions

  • Why is WP not rendering my Zero_Control_Typography::render_content() output?
  • Is there a necessary hook priority or missing argument I’m overlooking?
  • What’s the minimal, fool-proof way to ensure WP uses my custom control subclass rather than falling back?
  • Are there any Astra‐style patterns (specific enqueue hooks, control registration order) I should mimic?

Any guidance or working minimal example would be hugely appreciated—thanks!

array_map and filter_var return unexpected results

I have the following code when submitting a form

$data['item_cost'] = ( isset( $_POST['item-cost'] ) ? array_map( "filter_var", array_filter( $_POST['item-cost'] ), array( FILTER_VALIDATE_FLOAT ) ) : "" );

but the result returns the first item as valid and the other items as false. Here’s an example of the $_POST[‘item-cost’] value

array(3) {
  [0]=>
  string(4) "6.15"
  [1]=>
  string(4) "6.15"
  [2]=>
  string(4) "0.50"
}

and the resulting $data[‘item-cost’] value:

array(3) {
  [0]=>
  float(6.15)
  [1]=>
  bool(false)
  [2]=>
  bool(false)
}

I feel like I’m missing something obvious here? Thanks.

IMAP message_id not visible in some messages, php says it’s an empty string [closed]

The IMAP message_id in some messages has a nonzero strlen (e.g., 62) but the text is not visible if I echo it, and var_dump says it’s an empty string. If I use ord and chr to duplicate the string character by character it looks like a legit message_id but the reconstructed string is still not visible if I echo it, and var_dump still says it’s an empty string. Has anyone else encountered this? It’s like a ghost message_id. It’s there but it’s not there and I can’t do anything with it.

PHPUnit on Apache – how to capture “console” output?

I’m implementing the server API (for geni.com) in PHP. The server requires OAuth authentication, so I need a browser because this requires user input (to permit access to their account). THIS all works fine.

Now I want to use PHPUnit to test the whole thing. My index.php calls the testsuite, and I THINK the tests are running (no errors in log, and it continues running past the call). Obviously there is no console for the output.

So HOW can I capture the test results?

Converting a d.m.Y string to an SQL date [duplicate]

I have a podata column in an SQL string that says 04.22.2025

I want to convert this string to a date and compare it with today, how do I do this?

$sql_my_date = date('Y-m-d');
CONVERT(DATETIME, podata, 111) >= CAST('$sql_my_date' AS datetime)

does not work

GCP app sometimes losing session data after post

Starting some time yesterday afternoon, my PHP app hosted on GCP using App Engine sometimes (but not always) loses session data on submit. I’m using the following at the top of each page to handle POST data:

//if data passed via post, put it in session and reload page
if (isset($_POST['form_data'])) {
    $_SESSION['form_data'] = $dp->clean_input_data($_POST['form_data']);
    $_SESSION['action'] = 'submit';
    header("location: ".$_SERVER['REQUEST_URI']);
    die();
}

So every submit is effectively a redirect back to the same page. I have the same problem if I put data in $_SESSION and redirect to a different page. This has worked flawlessly for literally years…until yesterday. I have verified that the session exists and the session id is not changing. Sometimes it works fine but requires several tries. It is the same on a page that simply refreshes after changing a menu item vs one that accepts form data. I feel like something must have changed on the server side but am at a loss as to what it could be. AND I can’t seem to upgrade my GCP support to reach someone there.

Any ideas?

DataTables warning: table id=sales-table – Ajax error. For more information about this error, please see http://datatables.net/tn/7

I am new and i have faced this error on my application. When operate this application on localhost it will works fine but when i try to host this application on domain server it showing me like this error kindly give me a solution so i can do it thanks.

Following are my code

Screenshot 01

Screenshot 02

My Route file code

<?php

use IlluminateSupportFacadesRoute;
use AppHttpControllersHomeController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

Route::get('/', function () {
    return view('auth.login');
})->middleware('guest');

Auth::routes(['register' => false]);

Route::group(['middleware' => 'auth'], function () {
    Route::get('/home', 'HomeController@index')
        ->name('home');

    Route::get('/sales-purchases/chart-data', 'HomeController@salesPurchasesChart')
        ->name('sales-purchases.chart');

    Route::get('/current-month/chart-data', 'HomeController@currentMonthChart')
        ->name('current-month.chart');

    Route::get('/payment-flow/chart-data', 'HomeController@paymentChart')
        ->name('payment-flow.chart');
        // routes/web.php

Route::get('/export-cash-flow-overview', [HomeController::class, 'exportCashFlowOverview'])
->name('exportCashFlowOverview');

});

My Controller file code

 <?php
    
    namespace ModulesSaleHttpControllers;
    
    use ModulesSaleDataTablesSalesDataTable;
    use GloudemansShoppingcartFacadesCart;
    use IlluminateRoutingController;
    use IlluminateSupportFacadesDB;
    use IlluminateSupportFacadesGate;
    use ModulesPeopleEntitiesCustomer;
    use ModulesProductEntitiesProduct;
    use ModulesSaleEntitiesSale;
    use ModulesSaleEntitiesSaleDetails;
    use ModulesSaleEntitiesSalePayment;
    use ModulesSaleHttpRequestsStoreSaleRequest;
    use ModulesSaleHttpRequestsUpdateSaleRequest;
    
    class SaleController extends Controller
    {
    
        public function index(SalesDataTable $dataTable) {
            abort_if(Gate::denies('access_sales'), 403);
    
            return $dataTable->render('sale::index');
        }
    
    
        public function create() {
            abort_if(Gate::denies('create_sales'), 403);
    
            Cart::instance('sale')->destroy();
    
            return view('sale::create');
        }
    
    
        public function store(StoreSaleRequest $request) {
            DB::transaction(function () use ($request) {
                $due_amount = $request->total_amount - $request->paid_amount;
    
                if ($due_amount == $request->total_amount) {
                    $payment_status = 'Unpaid';
                } elseif ($due_amount > 0) {
                    $payment_status = 'Partial';
                } else {
                    $payment_status = 'Paid';
                }
    
                $sale = Sale::create([
                    'date' => $request->date,
                    'customer_id' => $request->customer_id,
                    'customer_name' => Customer::findOrFail($request->customer_id)->customer_name,
                    'tax_percentage' => $request->tax_percentage,
                    'discount_percentage' => $request->discount_percentage,
                    'shipping_amount' => $request->shipping_amount * 100,
                    'paid_amount' => $request->paid_amount * 100,
                    'total_amount' => $request->total_amount * 100,
                    'due_amount' => $due_amount * 100,
                    'status' => $request->status,
                    'payment_status' => $payment_status,
                    'payment_method' => $request->payment_method,
                    'note' => $request->note,
                    'tax_amount' => Cart::instance('sale')->tax() * 100,
                    'discount_amount' => Cart::instance('sale')->discount() * 100,
                ]);
    
                foreach (Cart::instance('sale')->content() as $cart_item) {
                    SaleDetails::create([
                        'sale_id' => $sale->id,
                        'product_id' => $cart_item->id,
                        'product_name' => $cart_item->name,
                        'product_code' => $cart_item->options->code,
                        'quantity' => $cart_item->qty,
                        'price' => $cart_item->price * 100,
                        'unit_price' => $cart_item->options->unit_price * 100,
                        'sub_total' => $cart_item->options->sub_total * 100,
                        'product_discount_amount' => $cart_item->options->product_discount * 100,
                        'product_discount_type' => $cart_item->options->product_discount_type,
                        'product_tax_amount' => $cart_item->options->product_tax * 100,
                    ]);
    
                    if ($request->status == 'Shipped' || $request->status == 'Completed') {
                        $product = Product::findOrFail($cart_item->id);
                        $product->update([
                            'product_quantity' => $product->product_quantity - $cart_item->qty
                        ]);
                    }
                }
    
                Cart::instance('sale')->destroy();
    
                if ($sale->paid_amount > 0) {
                    SalePayment::create([
                        'date' => $request->date,
                        'reference' => 'INV/'.$sale->reference,
                        'amount' => $sale->paid_amount,
                        'sale_id' => $sale->id,
                        'payment_method' => $request->payment_method
                    ]);
                }
            });
    
            toast('Sale Created!', 'success');
    
            return redirect()->route('sales.index');
        }
    
    
        public function show(Sale $sale) {
            abort_if(Gate::denies('show_sales'), 403);
    
            $customer = Customer::findOrFail($sale->customer_id);
    
            return view('sale::show', compact('sale', 'customer'));
        }
    
    
        public function edit(Sale $sale) {
            abort_if(Gate::denies('edit_sales'), 403);
    
            $sale_details = $sale->saleDetails;
    
            Cart::instance('sale')->destroy();
    
            $cart = Cart::instance('sale');
    
            foreach ($sale_details as $sale_detail) {
                $cart->add([
                    'id'      => $sale_detail->product_id,
                    'name'    => $sale_detail->product_name,
                    'qty'     => $sale_detail->quantity,
                    'price'   => $sale_detail->price,
                    'weight'  => 1,
                    'options' => [
                        'product_discount' => $sale_detail->product_discount_amount,
                        'product_discount_type' => $sale_detail->product_discount_type,
                        'sub_total'   => $sale_detail->sub_total,
                        'code'        => $sale_detail->product_code,
                        'stock'       => Product::findOrFail($sale_detail->product_id)->product_quantity,
                        'product_tax' => $sale_detail->product_tax_amount,
                        'unit_price'  => $sale_detail->unit_price
                    ]
                ]);
            }
    
            return view('sale::edit', compact('sale'));
        }
    
    
        public function update(UpdateSaleRequest $request, Sale $sale) {
            DB::transaction(function () use ($request, $sale) {
    
                $due_amount = $request->total_amount - $request->paid_amount;
    
                if ($due_amount == $request->total_amount) {
                    $payment_status = 'Unpaid';
                } elseif ($due_amount > 0) {
                    $payment_status = 'Partial';
                } else {
                    $payment_status = 'Paid';
                }
    
                foreach ($sale->saleDetails as $sale_detail) {
                    if ($sale->status == 'Shipped' || $sale->status == 'Completed') {
                        $product = Product::findOrFail($sale_detail->product_id);
                        $product->update([
                            'product_quantity' => $product->product_quantity + $sale_detail->quantity
                        ]);
                    }
                    $sale_detail->delete();
                }
    
                $sale->update([
                    'date' => $request->date,
                    'reference' => $request->reference,
                    'customer_id' => $request->customer_id,
                    'customer_name' => Customer::findOrFail($request->customer_id)->customer_name,
                    'tax_percentage' => $request->tax_percentage,
                    'discount_percentage' => $request->discount_percentage,
                    'shipping_amount' => $request->shipping_amount * 100,
                    'paid_amount' => $request->paid_amount * 100,
                    'total_amount' => $request->total_amount * 100,
                    'due_amount' => $due_amount * 100,
                    'status' => $request->status,
                    'payment_status' => $payment_status,
                    'payment_method' => $request->payment_method,
                    'note' => $request->note,
                    'tax_amount' => Cart::instance('sale')->tax() * 100,
                    'discount_amount' => Cart::instance('sale')->discount() * 100,
                ]);
    
                foreach (Cart::instance('sale')->content() as $cart_item) {
                    SaleDetails::create([
                        'sale_id' => $sale->id,
                        'product_id' => $cart_item->id,
                        'product_name' => $cart_item->name,
                        'product_code' => $cart_item->options->code,
                        'quantity' => $cart_item->qty,
                        'price' => $cart_item->price * 100,
                        'unit_price' => $cart_item->options->unit_price * 100,
                        'sub_total' => $cart_item->options->sub_total * 100,
                        'product_discount_amount' => $cart_item->options->product_discount * 100,
                        'product_discount_type' => $cart_item->options->product_discount_type,
                        'product_tax_amount' => $cart_item->options->product_tax * 100,
                    ]);
    
                    if ($request->status == 'Shipped' || $request->status == 'Completed') {
                        $product = Product::findOrFail($cart_item->id);
                        $product->update([
                            'product_quantity' => $product->product_quantity - $cart_item->qty
                        ]);
                    }
                }
    
                Cart::instance('sale')->destroy();
            });
    
            toast('Sale Updated!', 'info');
    
            return redirect()->route('sales.index');
        }
    
    
        public function destroy(Sale $sale) {
            abort_if(Gate::denies('delete_sales'), 403);
    
            $sale->delete();
    
            toast('Sale Deleted!', 'warning');
    
            return redirect()->route('sales.index');
        }
    }
    

    My SalesDataTable.php


<?php

namespace ModulesSaleDataTables;

use ModulesSaleEntitiesSale;
use YajraDataTablesHtmlButton;
use YajraDataTablesHtmlColumn;
use YajraDataTablesHtmlEditorEditor;
use YajraDataTablesHtmlEditorFields;
use YajraDataTablesServicesDataTable;

class SalesDataTable extends DataTable
{

    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query)
            ->addColumn('total_amount', function ($data) {
                return format_currency($data->total_amount);
            })
            ->addColumn('paid_amount', function ($data) {
                return format_currency($data->paid_amount);
            })
            ->addColumn('due_amount', function ($data) {
                return format_currency($data->due_amount);
            })
            ->addColumn('status', function ($data) {
                return view('sale::partials.status', compact('data'));
            })
            ->addColumn('payment_status', function ($data) {
                return view('sale::partials.payment-status', compact('data'));
            })
            ->addColumn('action', function ($data) {
                return view('sale::partials.actions', compact('data'));
            });
    }

    public function query(Sale $model)
    {
        return $model->newQuery();
    }

    public function html()
    {
        return $this->builder()
            ->setTableId('sales-table')
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->dom("<'row'<'col-md-3'l><'col-md-5 mb-2'B><'col-md-4'f>> .
                                'tr' .
                                <'row'<'col-md-5'i><'col-md-7 mt-2'p>>")
            ->orderBy(8)
            ->buttons(
                Button::make('excel')
                    ->text('<i class="bi bi-file-earmark-excel-fill"></i> Excel'),
                Button::make('print')
                    ->text('<i class="bi bi-printer-fill"></i> Print'),
                Button::make('reset')
                    ->text('<i class="bi bi-x-circle"></i> Reset'),
                Button::make('reload')
                    ->text('<i class="bi bi-arrow-repeat"></i> Reload')
            );
    }

    protected function getColumns()
    {
        return [
            Column::make('reference')
                ->className('text-center align-middle'),

            Column::make('date')
                ->className('text-center align-left'),

            Column::make('customer_name')
                ->title('Customer')
                ->className('text-center align-middle'),

            // Column::computed('status')
            //     ->className('text-center align-middle'),

            Column::computed('total_amount')
                ->className('text-center align-middle'),

            Column::computed('paid_amount')
                ->className('text-center align-middle'),

            Column::computed('due_amount')
                ->className('text-center align-middle'),

            Column::computed('payment_status')
                ->className('text-center align-middle'),

            Column::computed('action')
                ->exportable(false)
                ->printable(false)
                ->className('text-center align-middle'),

            Column::make('created_at')
                ->visible(false)
        ];
    }

    protected function filename()
    {
        return 'Sales_' . date('YmdHis');
    }
}
 
      

MY Model file code

<?php

namespace ModulesSaleEntities;

use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentFactoriesHasFactory;

class Sale extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function saleDetails() {
        return $this->hasMany(SaleDetails::class, 'sale_id', 'id');
    }

    public function salePayments() {
        return $this->hasMany(SalePayment::class, 'sale_id', 'id');
    }

    public static function boot() {
        parent::boot();

        static::creating(function ($model) {
            $number = Sale::max('id') + 1;
            $model->reference = make_reference_id('SL', $number);
        });
    }

    public function scopeCompleted($query) {
        return $query->where('status', 'Completed');
    }

    public function getShippingAmountAttribute($value) {
        return $value / 100;
    }

    public function getPaidAmountAttribute($value) {
        return $value / 100;
    }

    public function getTotalAmountAttribute($value) {
        return $value / 100;
    }

    public function getDueAmountAttribute($value) {
        return $value / 100;
    }

    public function getTaxAmountAttribute($value) {
        return $value / 100;
    }

    public function getDiscountAmountAttribute($value) {
        return $value / 100;
    }
}

MY View Resource file code

@extends('layouts.app')

@section('title', 'Sales')

@section('third_party_stylesheets')
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.25/css/dataTables.bootstrap4.min.css">
@endsection

@section('breadcrumb')
    <ol class="breadcrumb border-0 m-0">
        <li class="breadcrumb-item"><a href="{{ route('home') }}">Home</a></li>
        <li class="breadcrumb-item active">Sales</li>
    </ol>
@endsection

@section('content')
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <a href="{{ route('sales.create') }}" class="btn btn-primary">
                            Add Sale <i class="bi bi-plus"></i>
                        </a>

                        <hr>

                        <div class="table-responsive">
                            {!! $dataTable->table() !!}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('page_scripts')
    {!! $dataTable->scripts() !!}
@endpush

I am getting an error can someone help me with the api? [closed]

The service is checking and showing the stock but the number is not being purchased, where am I making a mistake?
Can you help me with this? Some people say parentheses but I don’t understand.

<?php

defined('BASEPATH') OR exit('No direct script access allowed');



class Fivesim_Api {

    function get_balance() {

        $api_key = get_instance()->config->item("fivesim_api_key");

        return explode(":",file_get_contents("http://api2.5sim.net/stubs/handler_api.php?api_key={$api_key}&action=getBalance"))[1];

    }

    public function get_number($country, $service) {

        $api_key = get_instance()->config->item("fivesim_api_key");

        $op = array_keys($this->get_cheapest($country,$service))[0];

        $res = file_get_contents("http://api2.5sim.net/stubs/handler_api.php?api_key={$api_key}&action=getNumber&operator={$op}&country={$country}&service={$service}");

        $data = explode(":", $res);

        if(count($data) != 3) {

            $error_code = 400;

            if($res == "NO_NUMBER") $error_code = 103;

            return array(

                "id" => 0,

                "number" => null,

                "error_code" => $error_code

            );

        }

        else {

            file_get_contents("http://api2.5sim.net/stubs/handler_api.php?api_key={$api_key}&action=setStatus&id={$data[1]}&status=1");

            return array(

                "id" => (int)$data[1],

                "number" => $data[2],

                "error_code" => 200

            );

        }

    }

    public function get_message($id) {

        $api_key = get_instance()->config->item("fivesim_api_key");

        $res = file_get_contents("http://api2.5sim.net/stubs/handler_api.php?api_key={$api_key}&action=getStatus&id={$id}");

        $data = explode(":", $res);

        if(count($data) > 1) {

            array_shift($data);

            file_get_contents("http://api2.5sim.net/stubs/handler_api.php?api_key={$api_key}&action=setStatus&id={$id}&status=6");

            return array(

                "code" => join(':', $data)

            );

        }

        else {

            return array(

                "code" => null

            );

        }

    }

    public function get_service_stock($country, $service) {

        $json = json_decode(file_get_contents("https://5sim.net/v1/guest/products/{$country}/any"), true);

        $json_service = $json[$service];

        return $json_service["Qty"];

    }

    public function get_countries() {

        $countries = array();

        $json = json_decode(file_get_contents("https://5sim.net/v1/guest/countries"), true);

        foreach(array_keys($json) as $country) {

            array_push($countries, array("id" => $country, "name" => $country));

        }

        return $countries;

    }

     public function get_countries_new() {

        $countries = array();

        $tr = array(

            "any" => "any",

            //"afghanistan" => "Afganistan",

            "albania" => "Arnavutluk",

            "algeria" => "Cezayir",

            "angola" => "Angola",

            "antiguaandbarbuda" => "Antigua ve Barbuda",

            "argentina" => "Arjantin",

            "armenia" => "Ermenistan",

            "austria" => "Avusturya",

            "azerbaijan" => "Azerbaycan",

            "bahrain" => "Bahreyn",

            "bangladesh" => "Bangladeş",

            "barbados" => "Barbados",

            "belarus" => "Belarus",

            "benin" => "Benin",

            "bhutane" => "Butan",

            "bih" => "Bosna Hersek",

            "bolivia" => "Bolivya",

            "botswana" => "Botsvana",

            "brazil" => "Brezilya",

            "bulgaria" => "Bulgaristan",

            "burkinafaso" => "Burkina Faso",

            "burundi" => "Burundi",

            "cambodia" => "Kamboçya",

            "cameroon" => "Kamerun",

            "canada" => "Kanada",

            "caymanislands" => "Cayman Adaları",

            "chad" => "Çad",

            "colombia" => "Kolombiya",

            "congo" => "Kongo",

            "costarica" => "Kosto Rika",

            "croatia" => "Hırvatistan",

            "cyprus" => "Kıbrıs",

            "czech" => "Çekya",

            "djibouti" => "Cibuti",

            "dominicana" => "Dominik Cumhuriyeti",

            "easrrimor" => "Doğu Timor",

            "ekvador" => "Ekvador",

            "egpty" => "Mısır",

            "englad" => "İngiltere",

            "equatorialguinea" => "Ekvator Ginesi",

            "estonia" => "Estonya",

            "ethiopia" => "Etiyopya",

            "finland" => "Finlandiya",

            "france" => "Fransa",

            "frenchguiana" => "Fransız Guyanası",

            "gabon" => "Gabon",

            "gambia" => "Gambiya",

            "georgia" => "Gürcistan",

            "germany" => "Almanya",

            "ghana" => "Gana",

            "guadeloupe" => "Guadeloupe",

            "guatemala" => "Guatemala",

            "guinea" => "Gine",

            "guineabissau" => "Gine-Bissau",

            "guyana" => "Guyana",

            "haiti" => "Haiti",

            "honduras" => "Honduras",

            "hungary" => "Macaristan",

            "india" => "Hindistan",

            "indonesia" => "Endonezya",

            "iran" => "İran",

            "iraq" => "Irak",

            "ireland" => "İrlanda",

            "israel" => "İsrail",

            "italy" => "İtalya",

            "djibouti" => "Cibuti",

            "ivorycoast" => "Fildişi Sahili",

            "jamaica" => "Jamaika",

            "jordan" => "Ürdün",

            "kazakhstan" => "Kazakistan",

            "kenya" => "Kenya",

            "kuwait" => "Kuveyt",

            "laos" => "Laos",

            "latvia" => "Letonya",

            "lesotho" => "Lesotho",

            "libya" => "Libya",

            "lithuania" => "Litvanya",

            "luxembourg" => "Lüksemburg",

            "macau" => "Makao",

            "madagascar" => "Madagaskar",

            "malawi" => "Malavi",

            "malaysia" => "Malezya",

            "maldives" => "Maldivler",

            "mali" => "Mali",

            "mauritania" => "Moritanya",

            "mauritius" => "Mauritius",

            "mexico" => "Meksika",

            "moldova" => "Moldova",

            "mongolia" => "Moğolistan",

            "montenegro" => "Karadağ",

            "morocco" => "Fas",

            "mozambique" => "Mozambik",

            "myanmar" => "Myanmar",

            "namibia" => "Namibya",

            "nepal" => "Nepal",

            "netherlands" => "Hollanda",

            "newzealand" => "Yeni Zelanda",

            "nicaragua" => "Nikaragua",

            "nigeria" => "Nijerya",

            "oman" => "Umman",

            "pakistan" => "Pakistan",

            "panama" => "Panama",

            "papuanewguinea" => "Papua Yeni Gine",

            "paraguay" => "Paraguay",

            "peru" => "Peru",

            "philippines" => "Filipinler",

            "poland" => "Polonya",

            "portugal" => "Portekiz",

            "puertorico" => "Porto Riko",

            "qatar" => "Katar",

            "reunion" => "Réunion",

            "romania" => "Romanya",

            "russia" => "Rusya",

            "rwanda" => "Ruanda",

            "saintkittsandnevis" => "Saint Kitts ve Nevis",

            "saintlucia" => "Saint Lucia",

            "saintvincentandgrenadines" => "Saint Vincent ve Grenadinler",

            "salvador" => "Salvador",

            "saudiarabia" => "Suudi Arabistan",

            "senegal" => "Senegal",

            "serbia" => "Sırbistan",

            "slovakia" => "Slovakya",

            "slovenia" => "Slovenya",

            "somalia" => "Somali",

            "southafrica" => "Güney Afrika",

            "spain" => "İspanya",

            "srilanka" => "Sri Lanka",

            "sudan" => "Sudan",

            "suriname" => "Surinam",

            "swaziland" => "Esvati̇ni̇",

            "sweden" => "İsveç",

            "syria" => "Suriye",

            "taiwan" => "Tayvan",

            "tajikistan" => "Tacikistan",

            "tanzania" => "Tanzanya",

            "thailand" => "Tayland",

            "trinidad and tobago" => "Trinidad ve Tobago",

            "togo" => "Togo",

            "tunisia" => "Tunus",

            "turkey" => "Türkiye",

            "turkmenistan" => "Türkmenistan",

            "uae" => "Birleşik Arap Emirlikleri",

            "uganda" => "Uganda",

            "uruguay" => "Uruguay",

            "ukraine" => "Ukrayna",

            "usa" => "Amerika",

            "uzbekistan" => "Özbekistan",

            "venezuela" => "Venezuela",

            "vietnam" => "Vietnam",

            "yemen" => "Yemen",

            "zambia" => "Zambiya",

            "zimbabwe" => "Zimbabve"

        );

        $json = json_decode(file_get_contents("https://5sim.net/v1/guest/countries"), true);

        foreach ($json as $c => $ct){

            if ($c !== "zimbabve")

         {

            array_push($countries, array(
                "name" => isset($tr[$c]) ? $tr[$c] : $ct["text_en"],
                "code" => $c,
                "isInBulk" => isset($tr[$c])
            ));

         }

        }

        return $countries;

    }





    public function get_cheapest($country, $service) {

        $ci =& get_instance();



        $ci->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));



        $key = "$country-$service";

        if (!$cheap = $ci->cache->get($key)) {

            $json = json_decode(file_get_contents("https://5sim.net/v1/guest/prices?country=$country&product=$service"),true);

            $arr = array();

            foreach ($json[$country][$service] as $operator => $data){

                if($data["count"] > 8){

                    array_push($arr, array(

                        $operator => $data["cost"]

                    ));

                }

            }



            usort($arr, function($a,$b){

                return array_values($a)[0] > array_values($b)[0];

            });

            $cheap = $arr[0];

            $ci->cache->save($key,$arr[0] , 900);



        }



        return $cheap;

    }



    public function get_service_price($country, $service) {

        $json = json_decode(file_get_contents("https://5sim.net/v1/guest/prices?country=$country&product=$product"), true);

        return max(array_column($json[$country][$service], 'cost')) . " RUB";

    }

    public function get_services_by_country($country) {

        $services = array();

        $api_key = get_instance()->config->item("fivesim_api_key");

        $json = json_decode(file_get_contents("http://api1.5sim.net/stubs/handler_api.php?api_key=$api_key&action=getNumbersStatus&country=$country"), true);

        foreach(array_keys($json) as $service) {

            if(strlen(explode("_",$service)[0]) > 2) {

                array_push($services, array(

                    "id" => explode("_",$service)[0],

                    "name" => explode("_",$service)[0])

                );

            }

        }

        return $services;

    }

    public function cancel_number($number_id) {

        $api_key = get_instance()->config->item("fivesim_api_key");

        file_get_contents("http://api2.5sim.net/stubs/handler_api.php?api_key={$api_key}&action=setStatus&id={$number_id}&status=-1");

    }

}

?>

The service is checking and showing the stock but the number is not being purchased, where am I making a mistake?
Can you help me with this? Some people say parentheses but I don’t understand.

Get last value of a sub-node in XML parsed by PHP into an array

I am trying to parse an Atom XML feed using PHP. It is for an ebook publisher. All is well, except I cannot work out how to extract the last “subject” tag for each entry: that is the publisher’s tag (instead of Library of Congress subject heading = LCSH), and there are a variable number of those for each title.

Here’s some sample code, and what I’ve got so far:

Feed XML (slightly abbreviated; three book’s worth)

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet href="https://standardebooks.org/feeds/atom/style" type="text/xsl"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/">
    <id>https://standardebooks.org/feeds/atom/new-releases</id>
    <link href="https://standardebooks.org/feeds/atom/new-releases" rel="self" type="application/atom+xml"/>
    <title>Standard Ebooks - Newest Ebooks</title>
    <subtitle>The 15 latest Standard Ebooks, most-recently-released first.</subtitle>
    <icon>https://standardebooks.org/images/logo.png</icon>
    <updated>2025-04-29T17:50:47Z</updated>
    <author>
        <name>Standard Ebooks</name>
        <uri>https://standardebooks.org</uri>
    </author>
    <link href="https://standardebooks.org/opensearch" rel="search" title="Standard Ebooks" type="application/opensearchdescription+xml"/>
    <entry>
        <id>https://standardebooks.org/ebooks/anthony-berkeley/the-poisoned-chocolates-case</id>
        <title>The Poisoned Chocolates Case</title>
        <author>
            <name>Anthony Berkeley</name>
            <uri>https://standardebooks.org/ebooks/anthony-berkeley</uri>
        </author>
        <published>2025-04-21T03:39:39Z</published>
        <updated>2025-04-21T09:01:35Z</updated>
        <rights>Public domain in the United States. Users located outside of the United States must check their local laws before using this ebook. Original content released to the public domain via the Creative Commons CC0 1.0 Universal Public Domain Dedication.</rights>
        <summary type="text">A club of amateur sleuths attempts to solve a crime whose solution has eluded Scotland Yard.</summary>
        <category scheme="http://purl.org/dc/terms/LCSH" term="Detective and mystery stories"/>
        <category scheme="http://purl.org/dc/terms/LCSH" term="London (England) -- Fiction"/>
        <category scheme="http://purl.org/dc/terms/LCSH" term="Sheringham, Roger (Fictitious character) -- Fiction"/>
        <category scheme="http://purl.org/dc/terms/LCSH" term="Police -- England -- London -- Fiction"/>
        <category scheme="https://standardebooks.org/vocab/subjects" term="Fiction"/>
        <category scheme="https://standardebooks.org/vocab/subjects" term="Mystery"/>
    </entry>
    <entry>
        <id>https://standardebooks.org/ebooks/g-k-chesterton/whats-wrong-with-the-world</id>
        <title>What’s Wrong with the World</title>
        <author>
            <name>G. K. Chesterton</name>
            <uri>https://standardebooks.org/ebooks/g-k-chesterton</uri>
        </author>
        <published>2025-04-29T03:11:02Z</published>
        <updated>2025-04-29T03:11:05Z</updated>
        <rights>Public domain in the United States. Users located outside of the United States must check their local laws before using this ebook. Original content released to the public domain via the Creative Commons CC0 1.0 Universal Public Domain Dedication.</rights>
        <summary type="text">Philosopher G. K. Chesterton comments on various social issues of his day, including property, imperialism, feminism, and education.</summary>
        <category scheme="http://purl.org/dc/terms/LCSH" term="Social problems"/>
        <category scheme="https://standardebooks.org/vocab/subjects" term="Nonfiction"/>
        <category scheme="https://standardebooks.org/vocab/subjects" term="Philosophy"/>
    </entry>
    <entry>
        <id>https://standardebooks.org/ebooks/george-gissing/the-private-papers-of-henry-ryecroft</id>
        <title>The Private Papers of Henry Ryecroft</title>
        <author>
            <name>George Gissing</name>
            <uri>https://standardebooks.org/ebooks/george-gissing</uri>
        </author>
        <published>2025-04-29T17:21:20Z</published>
        <updated>2025-04-29T17:49:20Z</updated>
        <rights>Public domain in the United States. Users located outside of the United States must check their local laws before using this ebook. Original content released to the public domain via the Creative Commons CC0 1.0 Universal Public Domain Dedication.</rights>
        <summary type="text">A retired Englishman muses on life and literature in his private diary.</summary>
        <category scheme="http://purl.org/dc/terms/LCSH" term="English fiction -- 19th century"/>
        <category scheme="https://standardebooks.org/vocab/subjects" term="Fiction"/>
    </entry>
</feed>

PHP code

<?php 
echo "<ol>". PHP_EOL;
$url = 'atom-sample.xml';

$xmla = simplexml_load_file($url);
  $xml = array();
  foreach($xmla->entry as $node) {
    $xml[] = $node;
  }

foreach($xml as $entry){
  $entry->registerXPathNamespace('ns','http://www.w3.org/2005/Atom');
  echo '<li>'.$entry->author->name .', <i>'. $entry->title .'</i> | '. $entry->category['term'] .'</li>'; 
  }
echo "</ol>";
?>

Parsed array (output of print_r($xml))

Array
(
    [0] => SimpleXMLElement Object
        (
            [id] => https://standardebooks.org/ebooks/anthony-berkeley/the-poisoned-chocolates-case
            [title] => The Poisoned Chocolates Case
            [author] => SimpleXMLElement Object
                (
                    [name] => Anthony Berkeley
                    [uri] => https://standardebooks.org/ebooks/anthony-berkeley
                )

            [published] => 2025-04-21T03:39:39Z
            [updated] => 2025-04-21T09:01:35Z
            [rights] => Public domain in the United States. Users located outside of the United States must check their local laws before using this ebook. Original content released to the public domain via the Creative Commons CC0 1.0 Universal Public Domain Dedication.
            [summary] => A club of amateur sleuths attempts to solve a crime whose solution has eluded Scotland Yard.
            [category] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => http://purl.org/dc/terms/LCSH
                                    [term] => Detective and mystery stories
                                )

                        )

                    [1] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => http://purl.org/dc/terms/LCSH
                                    [term] => London (England) -- Fiction
                                )

                        )

                    [2] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => http://purl.org/dc/terms/LCSH
                                    [term] => Sheringham, Roger (Fictitious character) -- Fiction
                                )

                        )

                    [3] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => http://purl.org/dc/terms/LCSH
                                    [term] => Police -- England -- London -- Fiction
                                )

                        )

                    [4] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => https://standardebooks.org/vocab/subjects
                                    [term] => Fiction
                                )

                        )

                    [5] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => https://standardebooks.org/vocab/subjects
                                    [term] => Mystery
                                )

                        )

                )

        )

    [1] => SimpleXMLElement Object
        (
            [id] => https://standardebooks.org/ebooks/g-k-chesterton/whats-wrong-with-the-world
            [title] => What’s Wrong with the World
            [author] => SimpleXMLElement Object
                (
                    [name] => G. K. Chesterton
                    [uri] => https://standardebooks.org/ebooks/g-k-chesterton
                )

            [published] => 2025-04-29T03:11:02Z
            [updated] => 2025-04-29T03:11:05Z
            [rights] => Public domain in the United States. Users located outside of the United States must check their local laws before using this ebook. Original content released to the public domain via the Creative Commons CC0 1.0 Universal Public Domain Dedication.
            [summary] => Philosopher G. K. Chesterton comments on various social issues of his day, including property, imperialism, feminism, and education.
            [category] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => http://purl.org/dc/terms/LCSH
                                    [term] => Social problems
                                )

                        )

                    [1] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => https://standardebooks.org/vocab/subjects
                                    [term] => Nonfiction
                                )

                        )

                    [2] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => https://standardebooks.org/vocab/subjects
                                    [term] => Philosophy
                                )

                        )

                )

        )

    [2] => SimpleXMLElement Object
        (
            [id] => https://standardebooks.org/ebooks/george-gissing/the-private-papers-of-henry-ryecroft
            [title] => The Private Papers of Henry Ryecroft
            [author] => SimpleXMLElement Object
                (
                    [name] => George Gissing
                    [uri] => https://standardebooks.org/ebooks/george-gissing
                )

            [published] => 2025-04-29T17:21:20Z
            [updated] => 2025-04-29T17:49:20Z
            [rights] => Public domain in the United States. Users located outside of the United States must check their local laws before using this ebook. Original content released to the public domain via the Creative Commons CC0 1.0 Universal Public Domain Dedication.
            [summary] => A retired Englishman muses on life and literature in his private diary.
            [category] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => http://purl.org/dc/terms/LCSH
                                    [term] => English fiction -- 19th century
                                )

                        )

                    [1] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => https://standardebooks.org/vocab/subjects
                                    [term] => Fiction
                                )

                        )

                )

        )

)

Output

<ol>
    <li>
        Anthony Berkeley,
        <i>The Poisoned Chocolates Case</i>
        | Detective and mystery stories
    </li>
    <li>
        G. K. Chesterton,
        <i>What’s Wrong with the World</i>
        | Social problems
    </li>
    <li>
        George Gissing,
        <i>The Private Papers of Henry Ryecroft</i>
        | English fiction -- 19th century
    </li>
</ol>

The value I’m after is the last one under [category], which is [5] for the first book, [2] for the second book, and [1] for the third book. Above, I’ve used $entry->category['term'] for this “slot”, which always returns the [0] value—but I want the last one, which is not consistent!

I am aware of the [last()] construct, but no permutation of my code using [last()] has worked. Obviously I’m doing something wrong in handling that sub-array with my approach/code. So what works?! Thanks!

How to encrypt and decrypt a file using gpg command using assymetric key? [duplicate]

For my laravel application, I need the gpg command to do encryption and decryption of CSV file using asymmetric key.

In my laravel application, I am already using symmetric key encryption and decryption using gpg command. But

Below is the command I used for encryption using symmetric key

exec("echo {$key} | gpg --passphrase-fd 0 --batch --yes -o {$filename['enc_name']} --armor --symmetric {$filename['name']}", $output, $retval);

Below is the command I used for decryption using symmetric key

 $fd = [ 0 => [ 'pipe', 'r'], 1 => [ 'pipe' , 'w' ] ];
proc_open("gpg --passphrase-fd 0 --batch -o $target -d $filename",
            $fd,
            $pipes,
            Storage::disk('rg-local')->path( '' )
        );

if( is_resource($process) )
        {
            fwrite( $pipes[0], $passphrase );
            fclose( $pipes[0] );

            $result = stream_get_contents( $pipes[1] );
            fclose( $pipes[1] );
            $retval = proc_close( $process );
            if($retval > 0)
            {
                Log::alert("Failed to decrypt file $filename. ProcOpen returned $retval. Error: $result");
                throw new Exception("Failed to decrypt file $filename. ProcOpen returned $retval. Error: $result");
            }
        }

For asymmetric encryption/decryption, I removed ‘–symmetric’ option from the above encryption command. But I got error as below (in laravel tinker)

>  fwrite( $pipes[0], $passphrase );
gpg: AES256.CFB encrypted data
= 5888

> fclose( $pipes[0] );gpg: encrypted with 1 passphrase
gpg: decryption failed: Bad session key