Home >php教程 >php手册 >PHP5中的SimpleXML解析XML文档

PHP5中的SimpleXML解析XML文档

WBOY
WBOYOriginal
2016-06-06 19:56:301293browse

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入 1、访问具有相同元素名称的节点 2、通过foreach循环所有相同元素名称的子节点 以下为引用的内容: foreach($xml-channel-item as $key=$value){ print “Title: ” . $item-title . “\n”; } 3、输出

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入

 

    1、访问具有相同元素名称的节点

    2、通过foreach循环所有相同元素名称的子节点

    以下为引用的内容:

    foreach($xml->channel->item as $key=>$value){

    print “Title: ” . $item->title . “\n”;

    }

    3、输出整个文档

    echo $xml->asXML();

    4、把节点作为字符串输出

    echo $xml->channel->item[0]->asXML();

    这将输出文本

    以下为引用的内容:

   

   

Braised Sea Cucumber

    //menu.example./dishes.php?dish=cuke

    Gentle flavors of the sea that nourish and refresh you.

   

    带文件名参数的asXML将会把原本输出的内容保存为一个文件

    $xml->channel->item[0]->asXML(“item[0].xml”);

    完整的代码:

    以下为引用的内容:

    rss.xml

   

   

   

   

What's For Dinner

    menu.example./

    These are your choices of what to eat tonight.

   

   

Braised Sea Cucumber

    menu.example./dishes.php?dish=cuke

    Gentle flavors of the sea that nourish and refresh you.

   

   

   

Baked Giblets with Salt

    menu.example./dishes.php?dish=giblets

    Rich giblet flavor infused with salt and spice.

   

   

   

Abalone with Marrow and Duck Feet

    menu.example./dishes.php?dish=abalone

    There's no mistaking the special pleasure of abalone.

   

   

   

    rss.php文件内容如下:

   

    $xml = simplexml_load_file(“rss.xml”);

    echo “

”.$xml->channel->title.“


”;

    echo “

    ”;

        echo “

  • Title:”.$xml->channel->item[0]->title.“
  • ”;

        echo “

  • Title:”.$xml->channel->item[1]->title.“
  • ”;

        echo “

  • Title:”.$xml->channel->item[2]->title.“
  • ”;

        echo “

”;

    print “Title: ” . $xml->channel->item[0]->title . “\n
”;

    print “Title: ” . $xml->channel->item[1]->title . “\n
”;

    print “Title: ” . $xml->channel->item[2]->title . “\n
”;

    echo “


”;

    foreach ($xml->channel->item[0] as $element_name => $content) {

    print “The $element_name is $content\n
”;

    }

    echo “


”;

    print_r($xml);

    echo $xml->channel->item[0]->asXML();

    ?>

    任何XML文本在输出前最好用 htmlentiteis() 函数编码后再输出,否这可能出现问题

  [1] [2] 

PHP5中的SimpleXML解析XML文档

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn