如何使用simplexml_load_string读取XML标记的值

时间:2018-04-12 03:23:46

标签: php xml

如何读取指令标记的值,即#34; DO IT"

 XML BLOB
 <Rate maxRate="HIGH" Type="PROD" situs="DESTINATION" inputOutputType="OUTPUT" FromParty="BUYER">
            <Instruction instructionLevel="DESIGN" instructionId="1234">DO IT</Instruction>

$xml = simplexml_load_string(XML BLOB);

输出:

$xml->Rate->Instruction = 

object(SimpleXMLElement)[95]
public '@attributes' => 
array (size=2)
  'instructionLevel' => string 'DESIGN' (length=7)
  'instrucctionId' => string '1234' (length=5)
public 0 => string 'DO IT' (length=11)

如何提取=&gt;做它

2 个答案:

答案 0 :(得分:2)

对于正确关闭<Rate>标记的blob:

$XML_BLOB = '
    <Rate maxRate="HIGH" Type="PROD" situs="DESTINATION" inputOutputType="OUTPUT" FromParty="BUYER">
        <Instruction instructionLevel="DESIGN" instructionId="1234">DO IT</Instruction>
    </Rate>';

$xml = simplexml_load_string($XML_BLOB);
$content = (string)$xml->Instruction;

php > var_dump($content);
string(5) "DO IT"

您可以使用标记名称作为对象的属性来访问Instruction元素。只需将其转换为字符串即可获取标记内容。

请注意,它不是$xml->Rate->Instruction,因为Rate是顶级节点。您的文档更有可能具有根/顶级节点:

$XML_DOC = '
    <root>
        <Rate maxRate="HIGH" Type="PROD" situs="DESTINATION" inputOutputType="OUTPUT" FromParty="BUYER">
            <Instruction instructionLevel="DESIGN" instructionId="1234">DO IT</Instruction>
        </Rate>
    </root>';

现在您将使用预期的层次结构访问它:

php > echo $xml->Rate->Instruction;
DO IT

或者,您可以使用Xpath表达式:

$instruction = $xml->xpath("Rate/Instruction");
$content = (string)$instruction[0];

php > var_dump($content);
string(5) "DO IT"

答案 1 :(得分:1)

$XML_BLOB = '
    <Rate maxRate="HIGH" Type="PROD" situs="DESTINATION" inputOutputType="OUTPUT" FromParty="BUYER">
        <Instruction instructionLevel="DESIGN" instructionId="1234">DO IT</Instruction>
    </Rate>';

$xml = simplexml_load_string($XML_BLOB);

foreach( $xml->xpath("//Instruction/text()") as $url ) {
    echo $url;
};