0

How to read the below xml using php?

<?xml version="1.0" encoding="UTF-8"?>

<video>

<youtube> youtube video url </youtube>

</video>

I tried the code below but seems not working:

$dom = new DOMDocument();

$dom->load('new_result.xml');

$results = $dom->documentElement;

foreach( $results  as $result)

{

foreach( $result->getElementsByTagName('youtube') as $youtube )

{

echo ' video url ' . $youtube->nodeValue;

}

}

3 Answers 3

2

try this :

if (file_exists('result.xml')) {
    $xml = simplexml_load_file('result.xml');

     echo $xml->youtube;
} else {
    exit('Failed to open result.xml.');
}
Sign up to request clarification or add additional context in comments.

1 Comment

Assuming that there's only one youtube element in the whole XML, of course.
0

No need for anything fancy, just use ->getElementsByTagName() method after you've loaded it up:

$dom->load('new_result.xml'); // load the file
// use ->getElementsByTagName() right away
$youtube = $dom->getElementsByTagName('youtube');
if($youtube->length > 0) { // if there are youtube nodes indeed
    foreach($youtube as $y) { // for each youtube node
        echo $y->nodeValue;
    }
}

Comments

0

The DOMDocument::documentElement is the root element node. In your XML, this would be the video element node. It is not a node list, but the actual node, so foreach will not work.

Just remove the outer foreach

$dom = new DOMDocument();
$dom->load('new_result.xml');
$video = $dom->documentElement;

foreach($video->getElementsByTagName('youtube') as $youtube) {
  echo ' video url ' . $youtube->nodeValue;
}

If you XML gets more complex you can use Xpath expressions:

$dom = new DOMDocument();
$dom->load('new_result.xml');
$xpath = new DOMXpath($dom);

foreach($xpath->evaluate('/video/youtube') as $youtube) {
  echo ' video url ' . $youtube->nodeValue;
}

Most Xpath expression will return node lists, but they can return scalar values. With that you can eliminate the second loop, too:

$dom = new DOMDocument();
$dom->load('new_result.xml');
$xpath = new DOMXpath($dom);

echo ' video url ' . $xpath->evaluate('string(/video/youtube[1])');

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.