How to split a single Text File TXT into Lines in PHP

Cloudmersive
2 min readApr 18, 2020

--

Having the ability to split up TXT files into more conveniently sized lines can be a great boon for any project, but then, you didn’t really need me to tell you that. What you do need is a way to get this done without having to waste all day trying to write out the solution yourself. I can do you one better: I’m going to show you how to add this functionality without spending more than 5 minutes.

Starting things out, we have our client installation first. This just means dropping this snippet into the command line of Composer.

composer require cloudmersive/cloudmersive_document_convert_api_client

From there, we are now in a position to make our function call for splitDocumentTxtByLine:

<?phprequire_once(__DIR__ . '/vendor/autoload.php');// Configure API key authorization: Apikey$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed// $config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('Apikey', 'Bearer');$apiInstance = new Swagger\Client\Api\SplitDocumentApi(// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.// This is optional, `GuzzleHttp\Client` will be used as default.new GuzzleHttp\Client(),$config);$input_file = "/path/to/file"; // \SplFileObject | Input file to perform the operation on.try {$result = $apiInstance->splitDocumentTxtByLine($input_file);print_r($result);} catch (Exception $e) {echo 'Exception when calling SplitDocumentApi->splitDocumentTxtByLine: ', $e->getMessage(), PHP_EOL;}?>

And just like that, give yourself a nice pat on the back. That’s right, we’re finished. For any TXT file that we input, we will be given back a response that is formatted into neat little lines.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet