如何从url获取xml上的特定数据并将其打印到php?

时间:2014-11-28 04:33:01

标签: php xml

我有这个工作的php xml代码:

<?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>

您注意到XML在代码中。我现在想要的只是从w3schools中消除该XML代码并替换或仅在此处获取http://www.w3schools.com/php/books.xml 。你可以帮助我吗,因为我被困了一个星期?

3 个答案:

答案 0 :(得分:0)

如果您想从外部来源加载,请使用simplexml_load_file()

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

What the output looks like

答案 1 :(得分:0)

检查以下

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

答案 2 :(得分:0)

试试这个:

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

简单!