First data pipeline with Flow PHP
Build the smallest pipeline: from_array() yields the rows, to_output() prints them, and nothing happens before run().
See the exampleShort programs, one function each, that you can run in the playground.
Build the smallest pipeline: from_array() yields the rows, to_output() prints them, and nothing happens before run().
See the exampleCall printSchema() on a DataFrame to see each column with its type; a ? marks a nullable column.
See the exampleRead the same CSV twice with from_csv(), once with an inferred schema and once with a declared one, and compare both with schema_to_ascii().
See the exampleFilter a DataFrame, add a column, then ask schema() for the result: the answer comes from the plan and not one row is read.
See the exampleRead a CSV file with one argument to from_csv(), keep two columns with select() and stop after three rows with limit().
See the exampleTurn rows that are already in memory, like API responses or fixtures, into a DataFrame with from_array() and let it infer the types.
See the exampleRead a CSV file row by row with from_csv(), set the delimiter and header, and get typed columns back.
See the exampleRead a JSON document that holds an array of objects with from_json(), one row per object, and select the columns you need.
See the exampleRead JSON Lines with from_json_lines(), one object per line, so a large file never has to fit in memory.
See the exampleRead XML node by node with from_xml() and withXMLNodePath(), then pick values out of each node with xpath().
See the exampleRead a columnar Parquet file with from_parquet(): the schema comes from the file, so no column type is guessed.
See the exampleRead an XLSX spreadsheet with from_excel(), rely on the default sheet and header handling, and select the columns you need.
See the exampleRead Flow's own binary format with from_floe(): the schema is stored in the file, so every type comes back exactly as written.
See the exampleSee how from_csv() names blank header cells, pads short lines with withMissingColumnsAsNull() and treats empty cells.
See the exampleRead query results through Doctrine DBAL: one query, many parameter sets, LIMIT and OFFSET pages or key set pagination.
Variants: Limit offset, Key set, Query, Queries
See the exampleWalk every page of a JSON API with from_http_paginated() and http_pagination_page_number(), and stop when a page comes back empty.
See the exampleRead a PostgreSQL table through the native client: a server side cursor, LIMIT and OFFSET pages or key set pagination.
Variants: Limit offset, Key set, Cursor
See the exampleKeep reading a CSV file past broken lines: withCorruptedRecords() writes each rejected record with its reason to a JSON Lines file.
See the exampleCollect every row into a PHP array passed by reference with to_array(), for tests or for code outside the pipeline.
See the exampleWrite rows to a CSV file with to_csv(); the header row and the order of the columns come from the schema.
See the exampleWrite JSON Lines with to_json_lines(): one JSON object per row and one row per line, ready to be read back line by line.
See the exampleWrite rows to an XML file with to_xml(), then echo the file back to see the nesting the writer produced.
See the exampleWrite a columnar, compressed Parquet file with to_parquet() using the schema of the frame, then read it back with from_parquet().
See the exampleWrite rows to an XLSX spreadsheet with to_excel(), with a header row from the schema, and read the file back with from_excel().
See the exampleWrite Flow's own binary format with to_floe(); the schema is stored in the file, so from_floe() reads every type back exactly.
See the exampleReduce each row to one column with concat_ws() and write it with to_text(), one line of the file per row.
See the exampleReplace what is already at the destination with overwrite(): read a CSV file and write it back to the same path without one column.
See the exampleRoute rows to different loaders by a condition with to_branch(), so one pass over the data writes two CSV files.
See the exampleSend rows to a database table through Doctrine DBAL in bulk: insert them, upsert them on a key, or delete the matching rows.
Variants: Insert, Upsert, Delete
See the exampleWrite rows to PostgreSQL through the native client: bulk insert, upsert on conflict, or several tables in one transaction.
Variants: Insert, Upsert, Transaction
See the exampleAdd or replace a column with withColumn(): compute it from another column with ref() or set a constant with lit().
See the exampleKeep only the columns you name with select() and drop the rest. Here it goes into the pipeline through with().
See the exampleChange the name of one column with rename() and leave the other columns and the row order as they are.
See the exampleRename many columns in one pass with renameEach() and rename_map(), an array of old name to new name.
See the exampleStrip or swap a part of every column name with rename_replace(): here the order_ prefix goes away.
See the exampleRewrite every column name into one naming style with rename_style(), here camelCase to snake_case, without listing the columns.
See the exampleChange the column order by sorting the schema: schema_sort_by_type_and_name() groups columns by type, then by name.
See the exampleGet the table back as a string with display() and a row limit, to log it, assert on it or embed it instead of printing it.
See the exampleBring a few rows back into PHP with fetch(), read one value from a column and turn the rows into arrays with toArray().
See the exampleRun the pipeline with forEach() and get every batch in a callback; read a batch by column with column('name')->values().
See the examplePut the same value into every row with lit() and withColumn(), for a marker column or a default value.
See the exampleCalculate a new column from two others with minus(), and keep both source columns in the row.
See the exampleGet the number of elements of a list or map column with size(), without unpacking the array.
See the exampleOrder a whole data set with sortBy() and reverse the direction with desc(). The sort has to see every row first.
See the exampleApply any PHP function to a column with call(): here explode splits a string into a list of integers, and you declare the result type.
See the exampleClean mixed string values with match_cases(): each match_condition() pairs a test with a result, the first hit wins, and a default covers the rest.
See the examplePack several steps into one reusable class that implements Transformation, and add it to the pipeline with with().
See the exampleReshape a column that holds arrays: expand its elements into rows, or unpack its keys into separate columns.
See the exampleKeep the rows that pass a condition with filter(): compare a column, a calculated value or the remainder of a division.
See the exampleSet a column from a condition with when(): if and else, a chain of conditions, a default for null, or an odd and even flag.
Variants: Basic, Odd, Null, Else when
See the exampleStop the source as soon as a condition fails with until(), and see why filter() on the same condition still reads every row.
See the exampleGroup rows with groupBy() and aggregate each group: count the rows of a group, or sum one of its columns.
Variants: Group by, Group by sum
See the exampleReduce a column to one value with aggregate(): one variant each for sum, average, min, max, first and last.
Variants: Sum, Average, Min, Max, First, Last
See the exampleTurn the values of one column into columns with pivot(), with the values declared up front or discovered from the data.
Variants: Declared values, Discovered values
See the exampleNumber the rows of each department 1, 2, 3 with row_number() over a window; tied salaries still get different numbers.
See the exampleRank salaries inside each department with rank() over a window: tied rows share a rank and the next rank skips ahead.
See the exampleRank salaries inside each department with dense_rank(): tied rows share a rank and the next rank follows with no gap.
See the exampleLimit the rows an aggregate sees with rowsBetween(): unbounded_preceding() gives a running total, preceding(1) a two-row moving average.
See the exampleMatch rows of two data sets on a shared column with join(): inner, left, right and anti join in one call.
See the exampleFetch the right side once per left batch with joinEach() and an ExtractorFactory, and keep only the unknown rows with JoinType::left_anti.
See the exampleJoin the same two data sets three times with JoinType::inner, left and right, and compare which rows each type keeps.
See the exampleInfer a schema from 100 rows of a CSV file, save it with schema_to_json() and load it with schema_from_json(), so later reads skip inference.
See the exampleDeclare the column types on a reader with withSchema() instead of inferring them, so NOT NULL columns stay NOT NULL.
See the exampleCheck a DataFrame against a declared schema with match(), and give from_array() the same schema so NOT NULL declarations can match.
See the examplePrint the schema instead of the rows with to_output(output: Output::schema); a key that some rows lack becomes a nullable column.
See the exampleMatch a row with an extra column against one schema twice: schema_evolving_validator() lets it through, schema_strict_validator() fails.
See the exampleBuild a schema from column definitions and nest fields with structure_schema() around type_structure(), then print it with schema_to_ascii().
See the exampleWrite one directory per column value with partitionBy(), and choose what happens when a partition exists: append, overwrite, ignore or fail.
Variants: Overwrite, Append, Ignore, Exception if exists
See the examplePut {color} and {sku} in the to_csv() path to name directories and files after partition values, and read them back with the same pattern.
See the exampleRead a partitioned directory with a glob path and get the partition columns back, also after append and overwrite.
Variants: Basic, After overwrite, After append
See the exampleFilter on a partition column with filter() and the reader never opens the directories that fail the condition, here color=green.
See the exampleGet one row per file with from_path_partitions(): the path, the partitions map and a column for each partition value.
See the exampleCut batches where a column value changes with batchBy(), so rows of one order stay together; constraint_sorted_by() guards the input order.
See the exampleMerge every batch into one with collect(), so the next step sees the whole data set at once. Memory grows with the data.
See the exampleSplit a data set into batches of two rows with batchSize() and watch to_output() print each batch on its own.
See the examplePass PhpBackend to config_builder()->backend() to opt out of the flow_php extension, then print the class and the values of each column.
See the exampleRead from_cache() with an HTTP extractor as the fallback and store the rows with cache(), so the next run skips the GitHub API call.
See the exampleGet the local filesystem with fstab(), write files as streams, list them by a glob pattern and read one back.
See the exampleOpen a write stream on stdout:// with fstab() and append lines straight to the process output, with nothing held in memory. Write-only.
See the exampleBuild aws_s3_filesystem() from a bucket and a client, write Parquet, CSV, XML, JSON and text files to aws-s3:// and read one back.
See the exampleBuild azure_filesystem() from an account and a shared key, write a Parquet file to azure-blob:// with to_parquet() and read it back.
See the exampleNarrow a value with type_integer()->assert(): it returns the value typed for static analysis and throws on the wrong type, with no coercion.
See the exampleConvert a string to an integer and to a date with cast() on type_integer() and type_date(), and catch the CastingException for bad input.
See the exampleAsk isValid() on type_integer() and type_json() whether a value has the type, and get a boolean for a condition, not an exception.
See the exampleCreate a tracer with tracer_provider(), open a span with attributes, nest a child span in it and print both with console_exporter().
See the exampleCreate a meter with meter_provider() and record values on a counter, a histogram, an up-down counter and a gauge.
See the exampleCreate a logger with logger_provider() and write info, debug, warn and error records, each with structured attributes.
See the exampleDetect host and process attributes with resource_detector(), merge custom ones from resource() over them and attach the result to every span.
See the exampleExtract traceparent and baggage headers with composite_propagator(), start a child span from them and inject the context into outgoing headers.
See the exampleWire a tracer, a logger and a meter into one telemetry() instance, so the spans, logs and metrics of one order share a resource and a context.
See the exampleDrop the batch a transformation failed in with ignore_error_handler() and keep going; with batchSize(1) only the failing row is lost.
See the exampleSee skip_rows_handler() drop the whole batch a failure landed in: with batchSize(2) the valid row beside the failing one goes too.
See the exampleStop the pipeline at the first failure with throw_error_handler(), the default, and catch the exception in the calling code.
See the example