简体   繁体   中英

How to fetch specific data on xml from url and print it to php?

I have this working php xml code:

<?php
    $str=<<<XML
<bookstore>
    <book category="COOKING">
        <title lang="en">Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
    <book category="CHILDREN">
        <title lang="en">Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
    </book>
    <book category="WEB">
        <title lang="en-us">XQuery Kick Start</title>
        <author>James McGovern</author>
        <year>2003</year>
        <price>49.99</price>
    </book>
    <book category="WEB">
        <title lang="en-us">Learning XML</title>
        <author>Erik T. Ray</author>
        <year>2003</year>
        <price>39.95</price>
    </book>
</bookstore>
XML;

    $data = new SimpleXMLElement($str);

?>

<table border>
    <tr>
        <th>Title</th>
        <th>Author</th>
        <th>Year</th>
        <th>Price</th>
    </tr>
    <?php
        foreach ($data->book as $book) {
            if ($book->price == 39.95) {
    ?>
    <tr>
        <td><?php echo $book->title; ?></td>
        <td><?php echo $book->author; ?></td>
        <td><?php echo $book->year; ?></td>
        <td><?php echo $book->price; ?></td>
    </tr>
    <?php
            }
        }
    ?>
</table>

You notice that XML is inside the code. All I want now is to eliminate that XML code and replace or just fetch it here http://www.w3schools.com/php/books.xml from w3schools. Can you help me sir cause I was stucked with this for a week?

Just use the simplexml_load_file() if you want to load it from an external source:

$data = simplexml_load_file('http://www.w3schools.com/php/books.xml');

What the output looks like

Check the following

$xml=simplexml_load_file('http://www.w3schools.com/php/books.xml');
var_dump($xml);

Try this:

$content = file_get_contents(' http://www.w3schools.com/php/books.xml '); echo $content;

Simple!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM