0

I'm trying to parse xml data by calling url via file_get_contents() in php. The result is:

<?xml version="1.0" encoding="UTF-8" ?>
<RESPONSE>
<SINGLE>
<KEY name="sitename"><VALUE>RedCross Test</VALUE>
</KEY>
<KEY name="username"><VALUE>test1</VALUE>
</KEY>
<KEY name="firstname"><VALUE>Test1</VALUE>
</KEY>
<KEY name="lastname"><VALUE>testTest1</VALUE>
</KEY>
</SINGLE>
</RESPONSE>

Here is the procedure:

<?php

header('Content-type: text/html; charset=utf-8');

$xml_obj = file_get_contents("http://localhost/example/webservice/rest/server.php?wstoken=".$token."&function=get_info");

$data = $xml_obj->SINGLE->KEY[2]->VALUE;
echo $data;

?>

The response is: error on line 2 at column 1: Notice: Trying to get property of non-object on line 7. Could someone advise me?

0

3 Answers 3

3

The error is stating that $xml_obj is not an object. That's because it's not. It's simply a var storing the contents (as a string) of the response from file_get_contents.

Instead of:

$xml_obj = file_get_contents("http://localhost/example/webservice/rest/server.php?wstoken=".$token."&function=get_info");

Try:

$xml_obj = simplexml_load_file("http://localhost/example/webservice/rest/server.php?wstoken=".$token."&function=get_info");

Or, if you need to use the contents for other stuff and want it in a separate variable:

$contents = file_get_contents("http://localhost/example/webservice/rest/server.php?wstoken=".$token."&function=get_info");

$xml = new DOMDocument();
$xml->loadXML( $contents );
Sign up to request clarification or add additional context in comments.

Comments

3

file_get_contents just returns the XML code as a string without parsing it. You probably want to use simplexml_load_file instead.

Comments

0

file_get_contents returns a STRING. e.g. raw xml. you need to load that string into DOM or Simple_XML before you can do the ->xxx stuff on it:

$xml = file_get_contents('...');
$dom = new DOMDocument();
$dom->loadXML($xml);
etc...

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.