0

I'm trying to load an XML file using:

$xml = simplexml_load_file('https://xxxxx/xxxxx.xml');

And XML file has some comments you can see in the pic below, which I'd like to use the data in the comments while creating my table:

Original XML File Comments

But when I tried to var_dump the data I see ["comments"] as:

["comment"]=>
  array(2) {
    [0]=>
    object(SimpleXMLElement)#5 (0) {
    }
    [1]=>
    object(SimpleXMLElement)#7 (0) {
    }
  }

Question is how could I retrieve the content of comments so I can use the lang names given in them?

1
  • Why on earth would you encode useful information as comments? Commented Feb 8, 2019 at 23:03

2 Answers 2

1

Use file_get_contents instead:

$xml = file_get_contents('https://xxxxx/xxxxx.xml');

If you need xml to load into object then I think you have to use DOMDocument():

$dom = new DOMDocument();
$dom->load('https://xxxxx/xxxxx.xml');
$xpath = new DOMXpath($dom);
$comment = $xpath->evaluate('string(//channel/item[1]/comment())');
echo $comment;

var_dump($xml); // showing comments

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I've solved it with a similar query like: /territory/languagePopulation/following::comment()[1]
1

You will need to use DOMDocument as SimpleXML isn't good for comments. You can use XPath to find the comment your after (use normalize-space() to remove spaces around the text) and following-sibling to return the following node. The last line just outputs the element it's found, you will need to process it as required (use [0] as query will return a list of nodes and you just want the first one).

$doc = new DOMDocument();
$doc->load($file);
$xp = new DOMXPath($doc);

$lang = "Finland";
$langPop = $xp->query("//comment()[normalize-space(.)='$lang']/following-sibling::*[1]");

echo $doc->saveXML($langPop[0]);

With some sample data...

<base>
    <!-- Finland -->
    <languagePopulation>Finland data
    </languagePopulation>
    <!-- England -->
    <languagePopulation>England data
    </languagePopulation>
</base>

will give

<languagePopulation>Finland data
    </languagePopulation>

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.