Fatal error uncaught typeerror cannot access offset of type string on string in

I get following error: PHP message: PHP Fatal error: Uncaught TypeError: Cannot access offset of type string on string on this line: if ($uploadZoneData[1]['size'] != 0) { On php 7.4 i had any tr...

I get following error:

PHP message: PHP Fatal error: Uncaught TypeError: Cannot access offset of type string on string

on this line:

if ($uploadZoneData[1]['size'] != 0) {

On php 7.4 i had any troube but with php 8 i have.

What can be the problem?

EDIT: Full code of the related functions:

function uploadSingleFile($zoneImage, $fileMoveTo, $fileAllowedExtensions, $fileAllowedSize, $zoneCustomer, $zone)
{
    global $config;

    // define file upload settings
    $errors = array();
    $fileName = $zoneImage['name'];
    $fileSize = $zoneImage['size'];
    $fileTmp = $zoneImage['tmp_name'];
    $fileType = $zoneImage['type'];
    $fileExt = strtolower(end(explode('.', $zoneImage['name'])));
    $MBtoByte = $fileAllowedSize * 1048576;
    $extensions= $fileAllowedExtensions;

    // define errors
    if (in_array($fileExt, $extensions) === false) {
        $errors[] = "Dieser Datei-Typ ist nicht erlaubt";
    }

    if ($fileSize > $MBtoByte) {
        $errors[] = 'Die Datei ist zu gross';
    }

    // finally try to upload the file
    if (empty($errors) == true) {
        $temp = explode(".", $zoneImage["name"]);
        $newfilename = $zoneCustomer . '-' . strtoupper($zone) . '-' . uniqid() . '.' . end($temp);

        move_uploaded_file($fileTmp, $_SERVER["DOCUMENT_ROOT"] . $fileMoveTo . $newfilename);
        $status = '1';
    } else {
        $status = '0';
    }

    // build array of the different outputs
    $uploadStatus = array($status, $newfilename, $errors);

    return $uploadStatus;
}

function updateZoneData($zoneFile, $zoneCustomer, $zone, $zoneLink, $maxWidth, $bannerID)
{
    global $db;

    // get customer values
    $getCustomerValues = getColumnValue('customers', "WHERE `customerNr` = '" . $zoneCustomer . "'");

    // define redirect url
    switch ($zone) {
      case "a1":
        $redirectZone = "zones.php#zones-overview-a1-overview";
      break;
      case "a2":
        $redirectZone = "zones.php#zones-overview-a2-overview";
      break;
      case "b1":
        $redirectZone = "zones.php#zones-overview-b1-overview";
      break;
      case "b2":
        $redirectZone = "zones.php#zones-overview-b2-overview";
      break;
      case "b3":
        $redirectZone = "zones.php#zones-overview-b3-overview";
      break;
      case "b4":
        $redirectZone = "zones.php#zones-overview-b4-overview";
      break;
      case "a9":
        $redirectZone = "zones.php#zones-overview-a9-overview";
      break;
      case "a9-1":
        $redirectZone = "zones.php#zones-overview-a9-1-overview";
      break;
      case "a11":
        $redirectZone = "zones.php#zones-overview-a11-overview";
      break;
      default:
        $redirectZone = "zones.php";
      }

    // upload file to the server
    $uploadZoneData = uploadSingleFile($zoneFile, '/adserver/banners/', array("jpg", "jpeg", "png", "gif"), '3', $zoneCustomer, $zone);

    if ($uploadZoneData[1]['size'] != 0) {
        if ($uploadZoneData[0] == '1') {

            // create ZIP-Backup (zone-banners) from '/adserver/banners' to '/cp/includes/files/zip-backups'
            createZipBackup('/adserver/banners', '/cp/includes/files/zip-backups', 'adserver-banners.zip');

            // get zone values & delete old bannerImg from file-system
            $getZoneDeleteValues = getColumnValue('zones', "WHERE `customerNr` = '" . $zoneCustomer . "' AND `zone` = '" . $zone . "' AND `id` = '" . $bannerID . "'");
            unlink($_SERVER["DOCUMENT_ROOT"] . '/adserver/banners/' . $getZoneDeleteValues['0']['bannerImg']);

            // execute action
            $updateZoneData = $db->update("zones", [
                                                   "customerNr" => $zoneCustomer,
                                                   "customer" => $getCustomerValues['0']['customer'],
                                                   "zone" => $zone,
                                                   "bannerImg" => $uploadZoneData[1],
                                                   "bannerLink" => $zoneLink,
                                                   "maxWidth" => $maxWidth,
                                                   "changeDate" => date("Y-m-d H:i:s")
                                                   ], [
                                                      "id" => $bannerID
                                                      ]);

            redirectTo($redirectZone, 1, "« " . strtoupper($zone) . "-Banner (" . $getCustomerValues['0']['customer'] . " [K. N°: " . $zoneCustomer . "]) » wurde erfolgreich aktualisiert.", 'ZONES');
        } else {

        // collect and save errors (file-upload)
            $collectedErrors = array_flatten($uploadZoneData[2]);
            setcookie("collectedErrors", '1', time() + (1 * 5), "/"); // expire in 5 seconds
            $_SESSION["collectedErrors"] = $collectedErrors;

            redirectTo($redirectZone, 0, "« " . strtoupper($zone) . "-Banner (" . $getCustomerValues['0']['customer'] . " [K. N°: " . $zoneCustomer . "]) » konnte nicht aktualisiert werden.", 'ZONES');
        }
    } else {

        // execute action
        $updateZoneData = $db->update("zones", [
                                               "customerNr" => $zoneCustomer,
                                               "customer" => $getCustomerValues['0']['customer'],
                                               "zone" => $zone,
                                               "bannerLink" => $zoneLink,
                                               "maxWidth" => $maxWidth,
                                               "changeDate" => date("Y-m-d H:i:s")
                                               ], [
                                                  "id" => $bannerID
                                                  ]);

        redirectTo($redirectZone, 1, "« " . strtoupper($zone) . "-Banner (" . $getCustomerValues['0']['customer'] . " [K. N°: " . $zoneCustomer . "]) » wurde erfolgreich aktualisiert.", 'ZONES');
    }
}

Comments

@Emdek

@bsweeney
bsweeney

linked a pull request

Aug 24, 2021

that will
close
this issue

bsweeney

added a commit
that referenced
this issue

Sep 2, 2021

@bsweeney

@bsweeney
bsweeney

linked a pull request

Sep 2, 2021

that will
close
this issue

bsweeney

added a commit
that referenced
this issue

Sep 11, 2021

@bsweeney

liam-milbel

added a commit
to Milestone-Belanova/dompdf
that referenced
this issue

Sep 16, 2021

* Moving the PDF version to a `const`

* Remove unused import

* Coding standards: Enable more PSR-2 rules

Enable rules which should be uncontroversial and easy to fix.

* Apply coding-standards changes to files

* Travis: Also check tests dir for coding standards

* Update IMagick version check logic

fixes dompdf#1296

* Fix scoping issue for IMagick version check

* fix Trying to access array offset on value of type null (dompdf#2227)

* fix Trying to access array offset on value of type null

* space

* fix css selector issue

* Fall back to decimals for roman numerals, if out of range

Consistent with how web browsers do it.

See https://en.wikipedia.org/wiki/Roman_numerals#Standard_form

* Stylesheet: Rename and document `_image` method for clarity

* Stylesheet: Make `resolve_url` public to reduce code duplication

* FontMetrics: Fix text-width calculations when using different backends

Fixes issue dompdf#2403.

* FontMetrics: Use direct access for protected properties

* Extend tests for resolving URLs in stylesheets

Without `$sheet->set_base_path(__DIR__)`, the stylesheet location would
be the location of phpunit.

* Fix instantiating CPDF Adapter without Dompdf

* Avoid offset error in CPDF line trasparency logic

related to dompdf#2227

* Use strict comparison in CPDF transparency logic

* Stylesheet: Improve return-value check

* Remove temporary file created when caching an image. (dompdf#2411)

* Remove temporary file created when caching an image.
dompdf#2377

* move unlink() to exception catch block

* Fix text-width calulation with letter spacing (dompdf#2414)

* Consistent doc for `get_text_width` arguments

To clear up the confusion about whether word and char spacing can be
float.

* CPDF: Fix text-width calulation with letter spacing

The letter spacing was counted twice for every space character.

* PDFLib: Fix text-width calculation with letter spacing

See discussion in dompdf#2414.

* Use OS-indepenent file path for unit test

* BlockFrameReflower: Always resolve `auto` widths

* Fix undefined variable (dompdf#2466)

* Bump version to 0.8.6

* Reset version string to commit hash

* Bump version to 1.0.1

* Reset version string to commit hash

* Bump version to 1.0.2

* Reset version string to commit hash

* Fix undefined variable

* Fix indentation

* Fix undefined variable

* Update src/FontMetrics.php

* Update src/FontMetrics.php

Co-authored-by: Brian Sweeney <brian@eclecticgeek.com>

* Add support for `page-break-before/-after` on table rows

pr dompdf#2512:

* Fix some typos

* Update documentation text for `_page_break_allowed`

Mainly to clear up a few unclear points that have changed. The comment
about table headers does not apply anymore.

* Add support for `page-break-before/-after` on table rows

Caveat: `page-break-after: always` does not work if the row is the last
of its table row group. I want to keep things simple now; this might be
better fixed in a proper rework of the page-break-properties handling,
e.g. by properly propagating the property values as per
https://www.w3.org/TR/css-break-3/#break-propagation.

Fixes dompdf#329

* BlockFrameReflower: Fixes to height calculations (dompdf#2511)

Brings the code closer to the spec:
* Always resolve `auto` heights
* Apply `min-/max-height` independently of the `overflow` property
value
* `min-height` overrules `max-height` (swapping removed)

* Prevent case exception in text renderer (dompdf#2423)

In case of " auto " width is throws an error as following and breaks the PDF render.
ErrorException: A non-numeric value encountered in /Path_To_Project/vendor/dompdf/dompdf/src/Renderer/Text.php:158

type casting the $width to float will prevent the ErrorException

* Resolve auto margins in more cases (dompdf#2531)

Fixes dompdf#1482

* Properly skip checking for page breaks on empty text nodes (dompdf#2506)

Before, page breaks before empty text nodes were not allowed, but they
were still checked; and as they report their line height as the space
needed, they could force a page break, which then would continue to
search backwards in the tree for an element that allowed a page break
(even though it would fit on the current page).

Based on work in dompdf#1356
Fixes dompdf#2468

* Fix table column widths after page break (dompdf#2502)

Node attributes are always string, so when a table was laid out, and
then a page break occurred before the table at a later point, `$colspan`
and `$rowspan` would always be string values and fail the checks below,
most notably the check where the minimum column width is set, so that
all columns received `0` minimum width.

Fixes dompdf#2395

* Add support for any inline-positioned frames in text alignment

This notably adds support for inline-block.

Fixes dompdf#1761

* Fix `justify` text alignment with letter spacing

The old logic seemed to correct for wrong text-width calculation
involving letter spacing when using the CPDF backend. With the fix in
dompdf#2414 this is no longer needed.

* Improve support for relative positioning

* Move handling of relative positioning to after the reflow process, so
that it does not affect layout.
* Handle `right` and `bottom` properties plus `auto` values (except for
RTL language support, which is an easy FIXME).
* As a side-effet, this adds support for relative positioning on inline
and inline-block elements.

Fixes dompdf#516

* Fix logic error in `add_frame_to_line` function

The block must check its own content-box width, not the content-box
width of its containing block when placing child frames.

Fixes dompdf#2476.

* Apply line shift to justified lines with break

* Tweak Style border/outline method color handling

fixes dompdf#2367

* BlockFrameReflower: Fix handling of `100%` width

The condition is wrong, as an `auto` width can resolve to more than
100% if the minimum width of the content is larger.

* BlockFrameReflower: Remove swapping of `min-/max-width`

Per spec, `min-width` overrules `max-width`.

https://www.w3.org/TR/CSS21/visudet.html#min-max-widths

* Remove erroneous ‘degenerate’ case handling in `get_min_max_width`

If the frame has no children, it might still have a fixed width set.

Fixes dompdf#2366

* Small code cleanups (dompdf#2547)

* Clean up `get_margin_height/width` functions

For simplicity, return a `float` value consistently.
The `get_break_margins` method was unused.

* TextReflower: Small cleanup for `get_min_max_width`

Also, add type declarations to `_collapse_white_space`.

* Clean up `split` method signatures

Consistent argument names and more type declarations.

Co-authored-by: Thomas Landauer <thomas@landauer.at>
Co-authored-by: Till Berger <till@mellthas.de>
Co-authored-by: Brian Sweeney <brian@eclecticgeek.com>
Co-authored-by: Edwin Manuel Cerrón Angeles <xerron.angels@gmail.com>
Co-authored-by: Ion Bazan <ion.bazan@gmail.com>
Co-authored-by: bradbulger <1234634+bradbulger@users.noreply.github.com>
Co-authored-by: Jáchym Toušek <enumag@gmail.com>
Co-authored-by: Madi <mudasser.ismail@gmail.com>

#php #json

Вопрос:

Использование Php 7.2

Краткое изложение проекта.

  • Я извлекаю файл json из Интернета в свой php-скрипт.
  • Расшифруйте json.
  • Отобразите информацию в таблице html.

Вот сценарий

 <?php
$url_meta               =   "LINK_TO_json" ;
$data_meta              =   file_get_contents($url_meta);
$result_meta            =   json_decode($data_meta);
?>


<table id="data-armours-1" class="table table-striped table-bordered">
    <thead>
        <tr>
                <th  class="align-middle">test</th>
        </tr>
    </thead>
    <tbody>
        <?php
            foreach($result_meta["Product"] as $key => $value) 
        {;?>
        <tr>
            <td class="align-middle"><?php echo $value["IsSuspended"];?></td>
            <td class="align-middle"><?php echo $value["*****"];?></td>
            <td class="align-middle"><?php echo $value["*****"];?></td>
            <td class="align-middle"><?php echo $value["*****"];?></td>
            <td class="align-middle"><?php echo $value["*****"];?></td>
            <td class="align-middle"><?php echo $value["*****"];?></td>
            .....
        </tr>
        <?php
        }?>
    </tbody>
</table>
 

Вар тупой для $result_meta

 var_dump ($result_meta );


string(2957684) "
{"Product":[
{
"IsSuspended":false,
"IsBlocked":false,
"IsPublishedOnWeb":true,
"IsServiceItem":false,
"IsSpecialProduct":false,
"Brand":"BraND",
"ProductionOrigin":1,
"HasVariationParent":false,
"HasVariationChild":false,
"IsTaxExempt":false,
"IsDiscountable":true,
"ProductDimensions":{
    "StockCode":"AB1010",
    "Length":235.00,
    "Height":160.00,
    "Width":20.00,
    "DimensionUnit":"mm",
    "Mass":0.20,
    "MassUnit":"Kg"
},
"TariffCode":"95030090",
"TariffDescription":"ABACUS",
"ProductDefaultCard":"",
"BarcodeType":"GTIN13",
"RetailPriceIncTax":*****,
"CustomerDiscount":*****,
"FriendlyTitle":"",
"PrintDescription":"",
"VariationMetaData":{
    "StockParentId":-1,
    "VariationFriendlyTitle":"",
    "VariationFriendlyStockCode":"",
    "OriginalStockCodeSuffixAndFootnote":""
},
"AttributeData":null,
"CompositeVariationFootnote":"",
"ExternalSiteWebURL":"",
"CustomerProductCode":null,
"TaxRate":0.150000,
"MaxDiscount":100.00,
"StockID":*****,
"StockCode":"*****",
"CustomerPrice":*****,
"CustomerTaxAmount":******,
"CustomerPriceWithTax":******,
"Description":"",
"ProductBarCode":"",
"FuturePrice":null,
"DetailedDescription":"
    rn
    Helps teach math skills
    rn
    
    rn
    
    rn

",
"RetailPrice":,
"IntermediatePacks":[
    {
        "PackBarCode":"",
        "PackQTY":,
        "StockCode":""
    },
    {
        "PackBarCode":"",
        "PackQTY":100,
        "StockCode":""
    }
],
"AlternativeProducts":[],
"ProductImageLinks":[""],
"ProductDocumentLinks":null,
"KitItems":[],
"PromotionInfo":null,
"WarehouseStockLevels":[    
    {
        "Amount":,
        "StockCode":"",
        "WarehouseCode":null,
        "WarehouseDescription":""
    }
],
"MainProductImageLink":"",
"TotalWarehouseStock":***,
"PublishingCategory":
    {
        "CategoryID":***,
        "CategoryName":"****"
    }
}
,{
"IsSuspended":false,
"IsBlocked":false,
"IsPublishedOnWeb":true,
"IsServiceItem":false,
"IsSpecialProduct":false,
"Brand":"BraND",
"ProductionOrigin":1,
"HasVariationParent":false,
"HasVariationChild":false,
"IsTaxExempt":false,
"IsDiscountable":true,
"ProductDimensions":{
    "StockCode":"AB1010",
    "Length":235.00,
    "Height":160.00,
    "Width":20.00,
    "DimensionUnit":"mm",
    "Mass":0.20,
    "MassUnit":"Kg"
},
"TariffCode":"95030090",
"TariffDescription":"ABACUS",
"ProductDefaultCard":"",
"BarcodeType":"GTIN13",
"RetailPriceIncTax":*****,
"CustomerDiscount":*****,
"FriendlyTitle":"",
"PrintDescription":"",
"VariationMetaData":{
    "StockParentId":-1,
    "VariationFriendlyTitle":"",
    "VariationFriendlyStockCode":"",
    "OriginalStockCodeSuffixAndFootnote":""
},
"AttributeData":null,
"CompositeVariationFootnote":"",
"ExternalSiteWebURL":"",
"CustomerProductCode":null,
"TaxRate":0.150000,
"MaxDiscount":100.00,
"StockID":*****,
"StockCode":"*****",
"CustomerPrice":*****,
"CustomerTaxAmount":******,
"CustomerPriceWithTax":******,
"Description":"",
"ProductBarCode":"",
"FuturePrice":null,
"DetailedDescription":"
    rn
    Helps teach math skills
    rn
    
    rn
    
    rn

",
"RetailPrice":,
"IntermediatePacks":[
    {
        "PackBarCode":"",
        "PackQTY":,
        "StockCode":""
    },
    {
        "PackBarCode":"",
        "PackQTY":100,
        "StockCode":""
    }
],
"AlternativeProducts":[],
"ProductImageLinks":[""],
"ProductDocumentLinks":null,
"KitItems":[],
"PromotionInfo":null,
"WarehouseStockLevels":[    
    {
        "Amount":,
        "StockCode":"",
        "WarehouseCode":null,
        "WarehouseDescription":""
    }
],
"MainProductImageLink":"",
"TotalWarehouseStock":***,
"PublishingCategory":
    {
        "CategoryID":***,
        "CategoryName":"****"
    }
}
]}"
 

Проблема

Я получаю следующую ошибку PHP

 Fatal error: Uncaught TypeError: Cannot access offset of type string on string in file/name/:linenumber Stack trace: #0 {main} thrown in file/name/:linenumber on line **
 

Желаемый результат

  • Может ли кто-нибудь, пожалуйста, посоветовать, как я отображаю эти данные JSON в таблице html?
  • Пожалуйста, обратите внимание, что не будут использоваться все данные.
  • но вам также нужно будет знать, как использовать «Промежуточные пакеты»: [].

Спасибо

Комментарии:

1. Как выглядела $data_meta?

2. Если это код, вызывающий эту ошибку, то один из элементов в $result_meta["Product"] нем является не массивом, а строкой. Это предполагает file/name/:linenumber , что часть сообщения об ошибке указывает на одну из строк, которая выводит a $value["*****"] в вашем foreach цикле.

3. @rickdenhaan если вы посмотрите на var_dump, весь $result_meta-это одна большая строка. Я подозреваю, что исходные данные были дважды закодированы.

4. @ADyson Хорошая мысль, я предположил, что на самом деле это была свалка $data_meta . Если это $result_meta так, то ваши подозрения, вероятно, верны.

5. Да, это строка JSON с двойным кодированием. Внешние метки и все»», чтобы избежать внутренних, выдают это. Это нужно исправить, это не должно было быть сохранено таким образом. Пусть тот, кто его создал, разберется с этим.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error uncaught smarty unable to load template file header tpl
  • Fatal error uncaught slim exception httpnotfoundexception not found in
  • Fatal error uncaught pdoexception could not find driver in
  • Fatal error uncaught exception serialization of simplexmlelement is not allowed
  • Fatal error uncaught exception error table

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии