How to read an XML file with PHP?

Asked

Viewed 1,619 times

1

Hello, I am trying to read an XML file through a link and am not succeeding.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">

</head>
<body>
<h1>Vagas de Trabalho</h1>
<?php
    $link = "https://api.vulpi.com.br/media/feeds/linkedin.xml"; 
    //link do arquivo xml
    $xml = simplexml_load_file($link) -> source; 
    //carrega o arquivo XML e retornando um Array

    foreach($xml -> job as $item){ 

        echo "<strong>Empresa:</strong> "
        .utf8_decode($item -> company)."<br />";
        echo "<strong>Titulo:</strong> "
        .utf8_decode($item -> title)."<br />";
        echo "<strong>Descrição:</strong> "
        .utf8_decode($item -> description)."<br />";
        echo "<strong>Url:</strong> "
        .utf8_decode($item -> applyUrl)."<br />";
        echo "<strong>Lugar:</strong> "
        .utf8_decode($item -> location)."<br />";
        echo "<strong>Lugar:</strong> "
        .utf8_decode($item -> salary)."<br />";
        echo "<br />";
    } //fim do foreach
?>
</body>
</html>

he error on line 17:

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\xml\vulpi.php on line 16

I looked at some examples and I’m right.. Someone can help me.?

  • When parsing the XML element root does not enter the DOM, so there is no need to access -> source as he did.

1 answer

1


No need to put source what is returned is all that is within that root, example:

<?php
    $link = "https://api.vulpi.com.br/media/feeds/linkedin.xml"; 
    $xml = simplexml_load_file($link); 
    foreach($xml -> job as $item)
    {     
        echo "<strong>Empresa:</strong> "
        .utf8_decode($item -> company)."<br />";
        echo "<strong>Titulo:</strong> "
        .utf8_decode($item -> title)."<br />";
        echo "<strong>Descrição:</strong> "
        .utf8_decode($item -> description)."<br />";
        echo "<strong>Url:</strong> "
        .utf8_decode($item -> applyUrl)."<br />";
        echo "<strong>Lugar:</strong> "
        .utf8_decode($item -> location)."<br />";
        echo "<strong>Lugar:</strong> "
        .utf8_decode($item -> salary)."<br />";
        echo "<br />";
    } //fim do foreach
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.