I have the following problem this code is supposed to take the first element of a list that is inside a datos.txt
that contains the following:
ph5986604c77db4
ph5988a83e37a80
ph5980f711d2b3b
ph5922205809bf2
ph593129a9631bb
ph5930d0950c8fa
ph5690ba39df654
ph593e778bc8219
I try to get the first line of data.txt usingfile()
$fil = file('datos.txt');
$id = $fil[0];
then use Curl
to get the page like this:
$url = 'http://sitio.com/embed/'.$id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch,CURLOPT_HEADER,0); //visualizar ñ y acentos.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate"); //(aceptación de codificación gzip)
$response = curl_exec($ch); //almacena el response de la pagina.
curl_close($ch);
echo $response;
But I don't get any results?
Whereas if I try it directly like this:
$url = 'http://sitio.com/embed/ph5986604c77db4';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch,CURLOPT_HEADER,0); //visualizar ñ y acentos.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate"); //(aceptación de codificación gzip)
$response = curl_exec($ch); //almacena el response de la pagina.
curl_close($ch);
echo $response;
If+i I get the page, so I am wondering where the fault is, I hope you can give me some idea.
The file() function returns an array of all lines including the trailing newline . That is, you are getting the value
"ph5986604c77db4\n"
(with\n
at the end).To avoid this, it is passed the option:
FILE_IGNORE_NEW_LINES
.FILE_SKIP_EMPTY_LINES
to avoid empty lines.If you only need one line of your file or if the file is too big, I think your code is not optimized using
file
.To read a certain row from a file you can search for that specific row. PHP has specific extensions for that.
In this case the extension
SplFileObject
1 could be interesting . It has a methodseek
which:You can build your own function to search for specific lines of a given file. Let's call our function
readFileByLine
(you can call it something else). It would be a function that you could incorporate into aClase
utility, it is much easier to use, especially if you need to do this type of operation in various parts of your application, or in different applications.For example:
Examples of use of the function:
NOTE: The function can be improved, verifying the existence of the file, the existence of the line being searched for, etc.
If you don't want to use this function, or if your PHP version is older than version
5.0.1
, you can make a similar function that opens the file and, using awhile
, finds the specified line.If the only line you care about is the first one, you can also get it like this:
1 As of PHP 5.1.0