how to proccess some tags in xml?

I’m trying to read an xml and its nodes with simplexml, I can open and display it in the browser with print_r for example, but I dont get take the nodes I need , can someone help me?
I need to get the value of the following tags, on tag Descritor I need everthing is inside it, then I´ve tag ContasCorrentes that is the main array, and inside it, I´ve many others tags on the same level, as DisponibilidadeFinanceira, DomicilioBancario, CredorFornecedor and etc…
So I´ve already gotten some values from those tags but some tags has the following format →
<gen:TipoDocumentoTESTEB1</gen:TipoDocumento>

So looks like that simplexml dont understant this part on that tag → gen: and on this way I dont get the data that I need :/

follows the LINK of the example file

the other parts of the xml I´m taking like this for tests, probably isnt the best way to do it but this is what i got ↓

$xml = simplexml_load_file("C:UsersThiagoDownloadsxml-teste.xml");

foreach ($xml->ContasCorrentes->DisponibilidadeFinanceira as $key) {
    $cont++;
    echo $key->ContaContabil . " controle = " . $cont . "</br>";    
}

$cont = 0;

foreach ($xml->ContasCorrentes->DomicilioBancario as $key) {
    $cont++;
    echo $key->CodigoAplicacao . " aplicacao cod = " . $cont . "</br>";    
}

So since then thanks for any help guys !

Laravel: orderby count on pivot while filtering parent with keyword

Good morning everybody,

I have two tables, users, questions and one pivot table users_questions. A question belongs to many users. A user has many questions.

users
-----
id | name

questions
---------
id | description

users_questions
---------------
user_id | question_id

I would like to get the top 3 users who asked the most questions for a specific keyword.

To search a keyword inside a question, I use a simple filter package. The code looks like that:

Questions::with('user')
        ->filter()
        ->paginate();

To get the 3 users who asked the most questions without filtering anything, I wrote this code:

UsersQuestions::with('user')
            ->select('mep_id')
            ->selectRaw('COUNT(*) AS count')
            ->groupBy('user_id')
            ->orderByDesc('count')
            ->limit(3)
            ->get();

But I can not figure out how to “mix” those two requests together.

Thanks in advance for your help!

PHP shortcode only displays 4 related blog posts on the page, but there are many more related

My PHP shortcode only displays 4 related blog posts on the page, but there are many more related. This is my shortcode:

function bloglink(){    
    global $taxonomy;
    $queried_object = get_queried_object();
    $term_id = $queried_object->term_id;
    $args = [
        'orderby' => 'ASC',
        'post_type' => 'blog',
        'tax_query' => [['taxonomy' => 'people',
        'field' => 'term_id',
        'terms' => $term_id,]]
    ];

    $loop = new WP_Query( $args );

    if ($loop->have_posts()) :
        $count = $loop->found_posts;
        $out .= '<a class="awithbackground" href="#taxonomycontent4"> Blogs ('.$count.')</a>';
    endif;

    return $out;
}

add_shortcode ('bloglink', 'bloglink');

I need some suggestons, thanks!

PHPUnit – test expected amount of items and check values

I am writing tests in PHP unit and as assertArraySubset() is deprecated I want to check that expected properties are sent and not more than the expected ones. Which I did:

    public function testPost(): void
    {
    $this->client->request(
        Request::METHOD_GET,
        self::ENDPOINT
        ),
        [],
        [],
        [
            'CONTENT_TYPE' => 'application/json',
        ]
    );

    $response = $this->client->getResponse();
    $responseBody = json_decode($response->getContent(), true);

    // compare structure (keys)
    $this->assertTrue(
        empty(array_diff_key($this->expected, $responseBody["data"][0])) &&
        empty(array_diff_key($responseBody["data"][0], $this->expected))
    );
}

Array:

 $this->expected = array(
        "meta" => json_decode('{"author": ["123-456-7890"], "category": ["www", "abc"]}', true),
        "post" => '{}',
        "scheduledTime" => 1641834440
    );

Also I want to cover two more cases but have not find a way for it:

  • That expected amount of posts are returned
  • That expected post is returned and has expected values for all
    properties.

How to draw a line graph with data in MySQL using chart Js in php

I want to draw a line graph using the following data in MySQL table.

date – dec 10 , dec 11, dec 12, dec 13, dec 14, dec 15, dec 16, dec17, dec,18,dec 19, dec 20
attendance – 65, 58, 56, 78, 51, 54, 69, 35, 68, 43, 52

I made two queries extracting the data and stored in 2 arrays namely $data1 and $data2 using the code below

$con = new mysqli($servername, $username, $password, $db);
$myquery1 = "select date from Table_attendance";
 $query1 = mysqli_query($con, $myquery1);
 
  if ( ! $query1 ) {
    echo mysqli_error();
    die;
  }
  
  for ($x = 0; $x < mysqli_num_rows($query1); $x++) {
  $data1[] = mysqli_fetch_assoc($query1);
}


 $my1 = "select attendance from Table_attendance";
 $qu1 = mysqli_query($con, $my1);
 
  if ( ! $qu1 ) {
    echo mysqli_error();
    die;
  }
  
  for ($x = 0; $x < mysqli_num_rows($qu1); $x++) {
  $data2[] = mysqli_fetch_assoc($qu1);
}

I then encoded the two arrays $data1 and $data2 into json format using the following code.

$encod = json_encode($data1);
$encod2 = json_encode($data2);

The output of the arrays were as follows.

[{“date”:”2021-12- 10″},{“date”:”2021-12-11″},{“date”:”2021-12-12″},{“date”:”2021-12-13″},{“date”:”2021-12-14″},{“date”:”2021-12-15″},{“date”:”2021-12-16″},{“date”:”2021-12-17″},{“date”:”2021-12-18″},{“date”:”2021-12-19″},{“date”:”2021-12-20″}]

[{“attendance “:”65”},{“attendance “:” 58 “},{“attendance “:” 56″},{“attendance”:” 78 “},{“attendance “:” 51 “},{“attendance “:” 54″}{“attendance “:”69 “},{“attendance “:”35”},{“attendance”:”68″},{“attendance”:”43″},{“attendance “:”52”}]

Finally I tried passing the encoded values as follows to plot into a line graph but it didn’t work.

<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<canvas id="myChart" style="width:100%;max-width:600px"></canvas>
<script>

var xValues = <?php echo $encod?>;
var yValues = <?php echo $encod2?>;

new Chart("myChart", {
  type: "line",
  data: {
    labels: xValues,
    datasets: [{
      fill: false,
      lineTension: 0,
      backgroundColor: "rgba(0,0,255,1.0)",
      borderColor: "rgba(0,0,255,0.1)",
      data: yValues
    }]
  },
  options: {
    title: {display: true, text: 'Custom Chart Title'},
    legend: {display: false},
    
                
                
                    
    scales: {
      yAxes: [{ticks: {min: 6, max:16}}],
    }
  }
});
</script>

Please help me with this assessment. If there is another better code than mine please be kind enough to share.

Cannot run laravel migration within docker compose

Sorry if this is obvious, I am quite new to docker…

I just want to connect a container with a laravel application to a postgres container

The Dockerfile of my laravel application is :

FROM php:7.4-fpm

RUN apt-get update && apt-get install -y libpq-dev
RUN docker-php-ext-install pdo pdo_pgsql pgsql
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

WORKDIR /app
COPY . /app
RUN composer install

CMD php artisan serve --host=0.0.0.0 --port=8181

EXPOSE 8181

No issues with this container that runs well

My docker-compose.yml goes like this :

version: '3'
services:
    laravel:
        container_name: app
        build:
            context: .
            dockerfile: Dockerfile
        environment:
            - DB_CONNECTION=pgsql
            - DB_HOST=localhost
            - DB_PORT=5432
            - DB_DATABASE=postgres
            - DB_USERNAME=postgres
            - DB_PASSWORD=postgres
        volumes:
            - .:/var/www/app
            - ./vendor:/var/www/app/vendor
        ports:
            - '8181:8181'
        command: bash -c "php artisan migrate"
        depends_on:
            - db
        links:
            - db
    db:
        image: postgres
        container_name: postgres_database
        restart: always
        environment:
            - POSTGRES_USER=postgres
            - POSTGRES_PASSWORD=postgres
            - POSTGRES_DB=postgres
        ports:
            - '5432:5432'
        volumes:
            - db:/var/lib/postgresql/data
volumes:
  db:
    driver: local

When I run docker-compose up I have an issue when running the migration command : I get a QueryException: could not find driver (SQL: select * from information_schema.tables where table_schema = public and table_name = migrations and table_type = 'BASE TABLE')

If I remove the command: bash -c "php artisan migrate" line in the docker-compose file, everything works fine and I can connect to my database using a database client

Does somebody know what is happening ?

Thanks a lot !!!

how to make checkbox by default checked in wordpress

i want to make checkbox by default as checked but i am using array format for checkbox which is given below. i am new to wordpress so don’t know much about parameters.

    add_action( 'woocommerce_review_order_before_submit','bt_add_checkout_checkbox', 10 );
/**
 * Add WooCommerce Checkbox checkout
 */
function bt_add_checkout_checkbox() {
   
    woocommerce_form_field( 'checkout-checkbox', array( // CSS ID
       'type'          => 'checkbox',
       'class'         => array('form-row mycheckbox'), // CSS Class
       'label_class'   => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
       'input_class'   => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
       'label'         => 'Ok I agree with <a href="/checkout-checkbox" target="_blank" rel="noopener">Checkout Checkbox Page</a>', // Label and Link
    ));    
}

this code is in function.php

so basically i want this checkbox as checked by defaul.

How can I wrapp odbc calls without modifing the way I do the calls in PHP?

Hi I am looking for a clean way to wrapp all my odbc calls with some error handling and logs without modifying all the code, but do it in an external way through overiding / define() / or reflexion. I dont knwo what to use or how to use it.

My application is actually using odbc directly in the code, and there is a lot of it, in class methods or in scripts directly.
We are currently trying to improve our performances and code quality, and without having logs, it is hard.
What I’d like to dot is to override ODBC by putting a decorator around it’s methods. Then this decorator execute ODBC, log queries / errors ect.

As you may think, it would be easier to just go over all the code and log. I could do that, but I am currently looking at this way to do because I don’t know to do it yet. It would be so much faster also to show my manager the avantages of having our own implementation of odbc wrapper.

Also i could just use it on local environement to find out wich queries are called multiple times or in loop.

I am just looking to do so for odbc_exec, odbc_prepare and odbc_execute. So no need to change the engine it self I believe

Any person having a snippet to share or an idea to solve this?

What is the best way to read xml data in php?

I’m a newbie 17 year old developer currently working at my internship project that consists into generating a PDF structure using PHP and TCPDF.
I’m having some issues reading the data from the xml file to display on the PDF structure. Here is a sample of the code I’ve tried:

$getfile = file_get_contents("ident.xml");
if ($getfile == FALSE)
{
    die('Failed to read.');
}
$arr = simplexml_load_string($getfile);
foreach ($arr->PromIdent as $d)
{
    $pdf->MultiCell(140, 10, $d,1,'L',false,1,'80','25',true,0,false,true,10,'B',false);
    $pdf->MultiCell(140, 10, $d['email'],1,'L',false,1,'80','25',true,0,false,true,10,'B',false);
}

That is my first time working with PHP and XML aswell, so be kind 🙂

Remembering text area value after refresh

Hi I’m trying here to remember the value that I put in this text area which is placed in a custom column, currently when I refresh the value disappears and I’m not sure how to do it any suggestions ? This is my temporary code. And I am trying to do this in WordPress in Woo Commerce. But I cannot find the answer I searched on Internet how I can do this but I cannot find anything anybody some suggestions ?

<?php

/**
 *                  _   _             _   
 *  __      ___ __ | | | | ___   ___ | |_ 
 *    / / / '_ | |_| |/ _  / _ | __|
 *    V  V /| |_) |  _  | (_) | (_) | |_ 
 *    _/_/ | .__/|_| |_|___/ ___/ __|
 *           |_|                          
 * -------------------------------------------
 * ------- code inspired from Hybrid, --------
 * -- Underscores Theme, Customizer Library --
 * -- (see readme file for copyright info.) --
 * -------------------------------------------
 *
 * :: Theme's main functions file ::::::::::::
 * :: Initialize and setup the theme :::::::::
 *
 * To modify this theme, its a good idea to create a child theme. This way you can easily update
 * the main theme without loosing your changes. To know more about how to create child themes 
 * @see http://codex.wordpress.org/Theme_Development
 * @see http://codex.wordpress.org/Child_Themes
 *
 * Hooks, Actions and Filters are used throughout this theme. You should be able to do most of your
 * customizations without touching the main code. For more information on hooks, actions, and filters
 * @see http://codex.wordpress.org/Plugin_API
 *
 * @package    Hoot Du
 */

/**
 * Run in Debug mode to load unminified CSS and JS, and add other developer data to code.
 * - You can set HOOT_DEBUG to true (default) for loading unminified files (useful for development/debugging)
 * - Or set HOOT_DEBUG to false for loading minified files (for production i.e. live site)
 * 
 * NOTE: If you uncomment this line, HOOT_DEBUG value will override any option for minifying
 * files (if available) set via the theme options (customizer) in WordPress Admin
 */
if (!defined('HOOT_DEBUG') && defined('SCRIPT_DEBUG') && SCRIPT_DEBUG)
    define('HOOT_DEBUG', true);

// Get the template directory and make sure it has a trailing slash.
$hoot_template_dir = trailingslashit(get_template_directory());

// Load the Core Hoot Framework Library files
require_once($hoot_template_dir . 'library/init.php');

// Load up the Theme files
require_once($hoot_template_dir . 'include/hoot-theme.php');

// For displaying in columns.

add_filter('manage_edit-shop_order_columns', 'set_custom_edit_shop_order_columnsex');
function set_custom_edit_shop_order_columnsex($columns)
{
    $columns['custom_column'] = __('Custom Column', 'your_text_domain');
    return $columns;
}


add_action('manage_shop_order_posts_custom_column', 'custom_shop_order_columnsex', 10, 2);
function custom_shop_order_columnsex($column)
{
    global $woocommerce, $post;
    echo '<div class="column_custom_field">';
    switch ($column) {

        case 'custom_column':
            ?>
                <div class="wrap">
                    <label for="header_scripts">Header Scripts</label>
                    <textarea name="header_scripts" class="large-text"><?php print $column; ?></textarea>
                    <button onClick="window.location.reload();">Update</button>
                    </form>
                </div>  
            <?php
            break;
        return $column;
    }
}

Google Drive API files:COPY returns 404 error

-With CURL ‘https://www.googleapis.com/drive/v3/files’ successfully works
-But at the same time ‘https://www.googleapis.com/drive/v3/files/{fileId}/copy’ throws 404 Error
-Have double checked the ‘fileId’.
-Have cleared the cache and tried but not working
-Have checked the Scope Permissions…
-The scopes are ‘https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.appdata https://www.googleapis.com/auth/drive.photos.readonly’
-The same example, If I Try on ‘Drive Explorer Try Now’, it works fine there as well
-So what’s wrong not able to figure out
$url = ‘https://www.googleapis.com/drive/v3/files/1ZYyl0MzfWy_V5Io3N0BTsF19pNiX7s23BqYPbQKplvU/copy’;

$ch = curl_init();      
curl_setopt($ch, CURLOPT_URL, $url);        
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));
$data = json_decode(curl_exec($ch), true);

$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);     

if($http_code != 200) 
    throw new Exception('Error : Failed');
    
return $data;

php upload multiple files from dynamic file fields

My app allow admins to create multiple file fields in order for user to upload 1 document per field, which will be recorded in database by input field name.

An example of the different fields that could be generated:

 <ul id="training_session_required_document_list" class="list-group">
 <li class="list-group-item d-flex px-0">
     <span class="col-6 my-auto">
         document 1*
     </span>
     <span class="col-6 my-auto">
         <input type="file" name="user_file_document-1" class="form-control user_file_field" value="">
     </span>
 </li>
 <li class="list-group-item d-flex px-0">
     <span class="col-6 my-auto">
         document-2*
     </span>
     <span class="col-6 my-auto">
         <input type="file" name="user_file_document-2" class="form-control user_file_field" value="">
     </span>
 </li>  
</ul>

Now when I process the Form and try to upload (with WordPress) files, only first in the loop is saved.

if ( isset($_FILES) && !empty($_FILES) ) {
    foreach ( $_FILES as $field => $metadata ) {
    $files = $_FILES[$field];
    $file = array(
        //Loop through all the uploaded files
        'name' => $files['name'],
        'type' => $files['type'],
        'tmp_name' => $files['tmp_name'],
        'error' => $files['error'],
        'size' => $files['size']
    );
    $_FILES = array( 'uploaded_file' => $file);
    $file_id = media_handle_upload('uploaded_file', $post_ID);
    if ( !is_wp_error( $file_id ) ) {
        /*
        * File uploaded successfully and you have the attacment id
        * Do your stuff with the attachment id here
        */
        update_post_meta( $post_ID, $field, $file_id);
    } else {
    }
  }
}

If I var_dump($_FILES) at the beginning I can view all my files info in 2 arrays for this example:

array (size=2)
  'user_file_document-1' => 
    array (size=5)
      'name' => string 'Screenshot_10.jpg' (length=17)
      'type' => string 'image/jpeg' (length=10)
      'tmp_name' => string 'C:wamp64tmpphp16A.tmp' (length=24)
      'error' => int 0
      'size' => int 102337
  'user_file_document-2' => 
    array (size=5)
      'name' => string 'Screenshot_12.jpg' (length=17)
      'type' => string 'image/jpeg' (length=10)
      'tmp_name' => string 'C:wamp64tmpphp16B.tmp' (length=24)
      'error' => int 0
      'size' => int 50005

How can I make my loop to save all the input files?

Laravel8 : syntax error, unexpected single-quoted string “)); ?>”> “, expecting “)

        <script type="text/javascript" src="{{ asset('/chart-area-demo.js') }}"></script>
        <script type="text/javascript" src="{{ asset('/chart-bar-demo.js') }}"></script>
        <script type="text/javascript" src="{{ asset('/datatables-demo.js') }}"></script>
        <script type="text/javascript" src="{{ asset('/datatables-simple-demo.js') }}"></script>
        <script type="text/javascript" src="{{ asset('/scripts.js') }}"></script>

These are my scripts, I do not understand what am I supposed to do, or what did I do wrong with them.
Also these are the unconverted scripts from laravel

        <script type="text/javascript" src="<?php echo e(asset('/chart-area-demo.js')); ?>"></script>
        <script type="text/javascript" src="<?php echo e(asset('/chart-bar-demo.js')); ?>"></script>
        <script type="text/javascript" src="<?php echo e(asset('/datatables-demo.js')); ?>"></script>
        <script type="text/javascript" src="<?php echo e(asset('/datatables-simple-demo.js')); ?>"></script>
        <script type="text/javascript" src="<?php echo e(asset('/scripts.js')); ?>"></script>