1

I am absolute beginner in PHP. Sorry for a very basic API question. I am stuck while coding at a point where I need to call a URL which will return me an XML or a JSON. Now I have to capture that in a variable.

For an example, I have written the following code:

class Search {
   private $documents = array();
   public function __construct() {
      $xmlDoc = new DOMDocument();
      $xmlDoc->load("solr.xml");
      .....

Now I am directly loading an XML. I dont want to do that, instead:

Step1: I want to call a http url which returns me an XML or JSON.
Step2: I need to store that in some variable like xmlDoc above
Step3: and later ofcourse I want to parse it.

I have no issues with step 3 but I just need some pointers or help as to how can I accomplish step 1 and 2?

2 Answers 2

4

load should accept a URL as a parameter.

$xmlDoc = new DOMDocument();
$xmlDoc->load('http://example.com/path/to/file.xml');

Or, you can use file_get_contents to download a URL to a string.

$xml = file_get_contents('http://example.com/path/to/file.xml');
$xmlDoc = new DOMDocument();
$xmlDoc->loadXML($xml);

Or for JSON:

$json = json_decode(file_get_contents('http://example.com/path/to/file.json'));
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks a lot Rocket!! Will this work on the fly, I mean I dont want to save XML file somewhere I just want to read the contents without IO i.e. whatever the URL returns
Yep it'll work on the fly. You don't need to save it to a file on your drive. It will download it to RAM.
@Rocket I think he actually wants to load it from a PHP page (see his Step 1). In that case load('example.com/xml.php?some_var=value') should do. The php page will read a database, create an XML file then display it, depending on the value of some_var.
@Ozzy: It doesn't matter where he wants to load it from (plus, he just said "from a url"). As long as the URL outputs the correct format, it can be whatever.
@chepe263: Why use cURL when $xmlDoc->load('http://example.com/path/to/file.xml'); is one line? :-P
0

For doing this with Json you first need a page which will have some json variables.

  1. You can do this by yourself by typing:

    $jsonVar = array('var1','var2'); // several variables
    echo encode_json($jsonVar);
    
  2. You can access these variables by typing:

    $jsonUrl = 'http://example.com/json.php';
    $jsonUrl = json_decode(file_get_contents($jsonUrl));
    
  3. To display one of these variables you can type:

    echo $jsonUrl[1]; // you can use print_r($jsonUrl); //for displaying the right array numbers to access the vars
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.