PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, February 18, 2022

[FIXED] Symfony4 how to call a file in public folder?

 February 18, 2022     symfony, symfony4     No comments   

Issue

I need to display a yaml file as an array but i but I can't display it.

I have create a service, and my controller call this service.

In my service i try to call my yaml like this :

$value = Yaml::parseFile('public\assets\organizations.yaml');
return $value;

But that return me that error :

File "public\assets\organizations.yaml" does not exist.

Solution

You are specifying the file with a relative path. This will not be resolved relative to the file it is in but relative to the current working directory you are in when executing the script. Since this depends on various factors it will always be troublesome.

Thus you should always use absolute paths. In symfony you can get the base path of your project via the kernel.project_dir configuration parameter. Your code does not provide enough context to understand how or where you are using it. But if it is inside a controller extending AbstractController you can use getParameter():

$projectDir = $this->getParameter('kernel.project_dir');
$absolutePath = $projectDir . '/public/assets/organizations.yml';

$value = Yaml::parseFile($absolutePath);
return $value;

Also note that using \ as the directory separator won't work under Linux/Unix-like systems where / is used as directory separator! Since / will work as directory separator under Windows, too, it is easiest to use it for cross-OS compatibility. Alternatively use the DIRECTORY_SEPARATOR constant.



Answered By - acran
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing