Search code examples
phpxmlxml-parsingnsxmlelement

php - xml data parsing


I am working on getting some xml data into a php variable so I can easily call it in my html webpage. I am using this code below:

$ch      = curl_init();
$timeout = 5;

$url = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/define?key=0b03f103-f6a7-4bb1-9136-11ab4e7b5294";

$definition = simplexml_load_file($url);

echo $definition->entry[0]->def;

However my results are: .

I am not sure what I am doing wrong and I have followed the php manual, so I am guessing it is something obvious but I am just not understanding it correctly.

The actual xml results from that link used in cURL are visible by clicking the link below , I did not post it because it is rather long:

http://www.dictionaryapi.com/api/v1/references/sd3/xml/test?key=9d92e6bd-a94b-45c5-9128-bc0f0908103d


Solution

  • <?php
    $ch = curl_init();
    $timeout = 5;
    
    $url = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/define?key=0b03f103-f6a7-4bb1-9136-11ab4e7b5294";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch); // you were missing a semicolon
    
    
    $definition = new SimpleXMLElement($data);
    echo '<pre>';
    print_r($definition->entry[0]->def);
    echo '</pre>';
    
    // this returns the SimpleXML Object
    
    
    // to get parts, you can do something like this...
    foreach($definition->entry[0]->def[0] as $entry) {
        echo $entry[0] . "<br />";
    }
    
    // which returns
    
    transitive verb
    14th century
    1 a
    :to determine or identify the essential qualities or meaning of 
    b
    :to discover and set forth the meaning of (as a word)
    c
    :to create on a computer 
    2 a
    :to fix or mark the limits of : 
    b
    :to make distinct, clear, or detailed especially in outline 
    3
    : 
    intransitive verb
    :to make a 
    

    Working Demo