PHP,SimpleXML,解析文档

时间:2011-08-11 22:31:55

标签: php xml parsing xpath simplexml

我是初学者,用php操纵或甚至阅读XML文档。

如果我有下面给出的XML文档,我将如何使用PHP解析和显示此XML文档的特定点(使用SimpleXML和/或xPath)......?

非常感谢您的帮助和基本示例!我会提供积极的反馈!

    <week id="1">
        <matchup id="1" date="09/08/11" time="8:30 P.M.">
            <away city="New Orleans">Saints</away>
            <home city="Green Bay">Packers</home>
            <final>
                <away score="">
                <home score="">
            </final>
        </matchup>
        <matchup id="2" date="09/11/11" time="1:00 P.M.">
            <away city="Atlanta">Falcons</away>
            <home city="Chicago">Bears</home>
            <final>
                <away score="">
                <home score="">
            </final>
        </matchup>
     </week>
    <week id="2">
        <matchup id="1" date="09/22/11" time="1:00 P.M.">
            <away city="Chicago">Bears</away>
            <home city="Tampa Bay">Buccaneers</home>
            <final>
                <away score="">
                <home score="">
            </final>
        </matchup>
        <matchup id="2" date="09/22/11" time="1:00 P.M.">
            <away city="Carolina">Panthers</away>
            <home city="St. Louis">Rams</home>
            <final>
                <away score="">
                <home score="">
            </final>
        </matchup>
     </week>

谢谢!

2 个答案:

答案 0 :(得分:1)

这是一个非常好的教程,任何人都不会失败

Using XML in PHP

也可以在这里阅读其余内容

Php for Beginnners

从页面引用:

<?xml version="1.0"?>
<pet>
    <name>Polly Parrot</name>
    <age>3</age>
    <species>parrot</species>
    <parents>
        <mother>Pia Parrot</mother>
        <father>Peter Parrot</father>
    </parents>
</pet>

PHP

<?php

// set name of XML file
$file = "pet.xml";

// load file
$xml = simplexml_load_file($file) or die ("Unable to load XML file!");

// access XML data
echo "Name: " . $xml->name . "\n";
echo "Age: " . $xml->age . "\n";
echo "Species: " . $xml->species . "\n";
echo "Parents: " . $xml->parents->mother . " and " .  $xml->parents->father . "\n";

?> 

答案 1 :(得分:0)

使用$xml = simplexml_load_file($file);$xml = simplexml_load_string($string);,您可以使用$xml输出print_r($xml);变量,以检查已解析输入的结构。这对理解如何操作输出非常有帮助。